Question

I am using preg_replace() in PHP with references. The problem is when the $1 reference is passed into another function (in this case escapeContent()) the value at run time is $1 instead of the actual replaced value. See the following:

function escapeContent($input) {
    return urlencode($input);
}

$content = '{{include:rec_ABXtI504839d1a607c1MI}}';
$content_smart_linked = preg_replace('/\{\{ ?include:([a-zA-Z0-9_]{25}) ?\}\}/i', '<a href="' . escapeContent('$1') . '">{{include:$1}}</a>', $content);
echo $content_smart_linked;

The echod result of $content_smart_linked is:

 <a href="%241">{{include:rec_ABXtI504839d1a607c1MI}}</a>

Notice urlencode() ran on $1, thus turning it into %241, instead of rec_ABXtI504839d1a607c1MI. If I remove urlencode() and just return $input, it works as expected.

Any ideas?

Was it helpful?

Solution

You have to use preg_replace_callback:

$content = '{{include:rec_ABXtI504839d1a607c1MI}}';
$content_smart_linked = preg_replace_callback('/\{\{ ?include:([a-zA-Z0-9_]{25}) ?\}\}/i', 
function($matches) {
   return '<a href="' . escapeContent($matches[1]) . '">{{include:'.$matches[1].'}}</a>';
},
$content);
echo $content_smart_linked;

Otherwise you need to use the DEPRECATED "\e" modifier which is highly not recommended (E_DEPRECATED will be emitted).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top