Search code examples
phpregexpreg-replacesubstr

substr() to preg_replace() matches php


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)?


Solution

  • 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):

    1. You have a syntax error, '$regex' is not going to work (they don't replace var names in single-quoted strings)
    2. You may want to look for better regexps to match URLs, you'll find plenty of them with a quick search
    3. You may want to run through htmlspecialchars() your matches (mainly problems with "&", but that depends how you escape the rest of the string.

    EDIT: Made it more PHP 4 friendly, requested by the asker.