Max Max - 1 year ago 81
PHP Question

substr() to preg_replace() matches php

I have two functions in PHP,

. I want to trim the urls extracted with
, to 20 characters for example. from

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
not a variable like
which could be easily trimmed with the function

The Question is how do I apply
something like this

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download