Reputation: 116
I have two functions in PHP, trimmer($string,$number)
and toUrl($string)
. I want to trim the urls extracted with toUrl()
, to 20 characters for example. from https://www.youtube.com/watch?v=HU3GZTNIZ6M
to https://www.youtube.com/wa...
function trimmer($string,$number) {
$string = substr ($string, 0, $number);
return $string."...";
}
function toUrl($string) {
$regex="/[^\W ]+[^\s]+[.]+[^\" ]+[^\W ]+/i";
$string= preg_replace($regex, "<a href='\\0'>".trimmer("\\0",20)."</a>",$string);
return $string;
}
But the problem is that the value of the match return \\0
not a variable like $url
which could be easily trimmed with the function trimmer()
.
The Question is how do I apply substr()
to \\0
something like this substr("\\0",0,20)
?
Upvotes: 3
Views: 472
Reputation: 1798
What you want is preg_replace_callback:
function _toUrl_callback($m) {
return "<a href=\"" . $m[0] . "\">" . trimmer($m[0], 20) ."</a>";
}
function toUrl($string) {
$regex = "/[^\W ]+[^\s]+[.]+[^\" ]+[^\W ]+/i";
$string = preg_replace_callback($regex, "_toUrl_callback", $string);
return $string;
}
Also note that (side notes wrt your question):
EDIT: Made it more PHP 4 friendly, requested by the asker.
Upvotes: 2