So I have this function to convert text URLs to links. What do I need to add to preg_replace
, to limit a long URL, currently it displays domain only, I would like to add a 4th attribute to this, that shows limit from full URL, limits the URL, I have no idea how to do this. This function is tested and works very well this is why I want to keep using it, how to I add this extra snippet for 4th attribute.
function autolink($str, $attributes=array()) {
$attrs = '';
foreach ($attributes as $attribute => $value) {
$attrs .= " {$attribute}=\"{$value}\"";
}
$str = ' ' . $str;
$str = preg_replace(
'|([\w\d]*)\s(https?://([\d\w\.-]+\.[\w\.]{2,6})[^\s\]\[\<\>]*/?)|i',
'$1 <a href="$2"'.$attrs.' title="$2" target="_blank" rel="nofollow">$3</a>',
$str
);
return $str;
}
Can someone please help me out.
INPUT:
$cont=autolink("https://www.example.com/test.php?ss=a https://www.example.com/2 https://www.exxxxxxxxxxxxxxxxxxaaample.com/3");
Output current:
<a href="https://www.example.com/test.php?ss=a" title="https://www.example.com/test.php?ss=a" target="_blank" rel="nofollow">www.example.com</a> <a href="https://www.example.com/2" title="https://www.example.com/2" target="_blank" rel="nofollow">www.example.com</a> <a href="https://www.exxxxxxxxxxxxxxxxxxaaample.com/3" title="https://www.exxxxxxxxxxxxxxxxxxaaample.com/3" target="_blank" rel="nofollow">www.exxxxxxxxxxxxxxxxxxaaample.com</a>
WANTED output:
<a href="https://www.example.com/test.php?ss=a" title="https://www.example.com/test.php?ss=a" target="_blank" rel="nofollow">www.example.com/test...</a> <a href="https://www.example.com/2" title="https://www.example.com/2" target="_blank" rel="nofollow">www.example.com/2</a> <a href="https://www.exxxxxxxxxxxxxxxxxxaaample.com/3" title="https://www.exxxxxxxxxxxxxxxxxxaaample.com/3" target="_blank" rel="nofollow">www.exxxxxxxxxxxxx.....</a>
I should be able to limit the URL name to like 40 chars. Anyways the third attribute is not needed and would be modified, not returning the domain, but the real name of URL limited to 40 chars.