简体   繁体   English

我正在用PHP练习RegEx。 为什么这个简单的regExp不起作用?

[英]I am practicing RegEx in PHP. Why doesn't this simple regExp work?

I am practicing RegEx in PHP. 我正在用PHP练习RegEx。 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. 我知道将它用于HTML字符串操作并不是那么好,但有时在我使用的PHP环境中DOMDocument不可用。

$a ='bsrc="lalala"';

$t = preg_replace('/(src="([^"]*)")/i', '\2', $a);

So I am trying to get lalala from the string but for some reasons it doesn't work. 所以我试图从字符串中获取lalala但由于某些原因它不起作用。 I got blalalaa in return; 我得到了blalalaa作为回报;

I tried escaping the " and write '/(src=\\"([^\\"]*)\\")/i' but to no avail. 我试图逃避"和写'/(src=\\"([^\\"]*)\\")/i'但无济于事。 I am doing it in a preg_replace_callback function, can that be the reason? 我在preg_replace_callback函数中执行此操作,这可能是原因吗?

Appreciate any help! 感谢任何帮助!

You should change your regular expression as 您应该将正则表达式更改为

src=\"([^\"]*)\"

正则表达式可视化

Debuggex Demo Debuggex演示

Final PHP must be 最终的PHP必须是

$t = preg_replace('~src=\"([^\"]*)\"~i', '\2', $a);

If you are trying to get a match then you need to use preg_match instead of preg_replace : 如果你想获得匹配,那么你需要使用preg_match而不是preg_replace

$a ='<src="lalala"a';
if (preg_match('/<src="([^"]*)"/i', $a, $m))
    print_r($m[1]);

This is because you are searching for <src and the string does not have this. 这是因为您正在搜索<src并且字符串没有这个。 Your test string should be <src="lalala" and not bsrc.. 你的测试字符串应该是<src="lalala"而不是bsrc..

Try this: 尝试这个:

    $a ='bsrc="lalala"a';

    if (preg_match('/src="(.*)"/i', $a, $matches))
    {
            if (isset($matches[1]))
            {
                 echo "Found value: " .$matches[1]. "\n";
            }
            else 
            {
                echo "Not found\n";
            }
    }
    else
    {
        echo "Not found\n";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM