0

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').'</a>' , $text);

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

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

2

Are you looking for php_replace_callback()?

Perform a regular expression search and replace using a callback

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.