views:

84

answers:

2

Does not work, the $1-value is lost when calling the function:

echo preg_replace('"\b(http://\S+)"', '<a href="$1">'.findTopDomain('$1').'</a>', $text);

Works fine, outputs: stackoverflow.com

echo preg_replace('"\b(http://\S+)"', '<a href="$1">'.findTopDomain('http://stackoverflow.com/questions/ask').'&lt;/a&gt;' , $text);

I need to send the $1 value to a function from within preg_replace. What am I doing wrong?

+2  A: 

You need to set the e modifier to have the substitution expression to be executed:

preg_replace('"\b(http://\S+)"e', '"<a href=\\"$1\\">".findTopDomain("$1")."</a>"', $text)

Note that your substitution now has to be a valid PHP expression. In this case the expression would be evaluated to:

"<a href=\"$1\">".findTopDomain("$1")."</a>"

And don’t forget to escape the output with at least htmlspecialchars:

preg_replace('"\b(http://\S+)"e', '"<a href=\\"".htmlspecialchars("$1")."\\">".htmlspecialchars(findTopDomain("$1"))."</a>"', $text)
Gumbo
+2  A: 

Are you looking for php_replace_callback()?

Perform a regular expression search and replace using a callback

Pekka