0

I am using following code for convert url to hyperlink on text.But the problem is i want to use shorten title for hyperlink for example this is url http://stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted and after convert like this :

<a href="http://stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted">http://stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted</a>

I want to this :

<a href="http://stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted">http://stackoverflow.com/...</a>

This is my code :

$stringdata = preg_replace('|([\w\d]*)\s?(https?://([\d\w\.-]+\.[\w\.]{2,6})[^\s\]\[\<\>]*/?)|i', '$1 <a href="$2" target="_blank">$2</a>', $stringdata);

Title should be shorten but url should be same of original.

Thankyou.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
Blueffect
  • 1
  • 1

2 Answers2

1

You could always use parse_url found here

Here's an example:

$url = 'http://www.stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted';

$splitUrl = parse_url($url);

echo '<a href="' . $url . '"/>' . $splitUrl['scheme'] . '://' . $splitUrl['host'] .'/... </a>';

parse_urlcreates an array from the URL provided.

UPDATE: Using Mikael Roos answer at that link I came up with what you needed it to do.

function make_clickable($text) {
    $regex = '#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#';
    return preg_replace_callback($regex, function ($matches) {
        $splitUrl = parse_url($matches[0]);
        return "<a href='{$matches[0]}'>{$splitUrl['scheme']}://{$splitUrl['host']}/..</a>";
    }, $text);
}

echo make_clickable('Some odd text here that makes https://stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted clickable');
Community
  • 1
  • 1
  • Hi i should detect all url on a text, i can change only one url my problem is i want to change all urls same technics on a text. – Blueffect Oct 26 '16 at 14:57
  • I do feel the need to warn you that if the text is user provided, you should sanitize it first, as this function will not sanitize it and will in fact execute unwanted JS on visitors pages. Read more about it https://www.owasp.org/index.php/Cross-site_Scripting_(XSS) –  Oct 26 '16 at 16:18
0

try this

$var='http://stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted';

$array=explode('/', $var);

$url=$array[0]."//".$array[2]."/...";
viral barot
  • 631
  • 4
  • 8
  • Sorry but text may include text and more than one url for example : Text : Bla bla bla bla bla http://stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted bla bla bla http://stackoverflow.com/questions/ask?title=blabla – Blueffect Oct 26 '16 at 13:32