Why doesn't preg_match work in a function of preg_replace_callback

I know it is not that good to use it for HTML string manipulation but there are times when DOMDocument is not available in the PHP environment I work with.

preg_replace_callback($pattern, function ($matches) {

    $z = $matches[2];
    preg_match('/src="([^"]*)"/i', $z, $t);

    //a lot of string manipulation going on here

    return $t[0].'and'.$matches[2];

}, $content_taken_FROM_HTML);

The $matches[1] here is 'src="a.jpg"';

If I put $z='src="a.jpg"', it works. But as long as I leave it as $z= $matches[1];, which should give the same string, it doesn't work.

What is going on here? And how can this be solved?

Upvotes: 1

Views: 105

Answers (1)

The " in the original string is escaped by \, probably caused by a built-in in preg_replace_callback() for $matches.

Should have stripslashes(), my friends!

stripslashes()

Un-quotes a quoted string.

Thanks anubhava for suggesting var_dump($matches). A good way to debug indeed!

Upvotes: 1

Related Questions