为什么preg_match不能在preg_replace_callback的函数中工作 [英] Why doesn't preg_match work in a function of preg_replace_callback

查看:89
本文介绍了为什么preg_match不能在preg_replace_callback的函数中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用它进行HTML字符串操作并不是那么好,但有时DOMDocument在我使用的PHP环境中不可用。


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

//大量字符串操作在这里执行

返回$ t [0]。'和'。$ matches [2];

},$ content_taken_FROM_HTML);

$ matches [1] 在这里是'src =a.jpg';



如果我把 $ z ='src =a.jpg',它可以工作,但只要我离开它作为 $ z = $ matches [1]; ,它应该给出相同的字符串,它不起作用。

\ 转义,可能是由内置的 preg_replace_callback()用于 $匹配



code> stripslashes(),我的朋友!


stripslashes()



取消引号引用的字符串。

感谢anubhava提示 var_dump ($匹配)。调试的好方法!


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?

解决方案

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!

这篇关于为什么preg_match不能在preg_replace_callback的函数中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆