在带引号的文本中使用转义引号的正则表达式

4

我有一个 PHP preg_match_all 和正则表达式问题。

我有以下代码:

<?php

$string= 'attribute1="some_value" attribute2="<h1 class=\"title\">Blahhhh</h1>"';

preg_match_all('/(.*?)\s*=\s*(\'|"|&#?\w+;)(.*?)\2/s', trim($string), $matches);

print_r($matches);

?>

似乎无法捕获我想要传递带引号的HTML实例中的转义引号。我已经尝试了许多基本引号内引号REGEX修复解决方案,但似乎没有一种适合我。我无法在这个现有的REGEX中正确放置它们。

我不是一个REGEX专家,请问有人可以指点我正确的方向吗?

我想要实现的结果是这样的:

Array
(
    [0] => Array
        (
            [0] => attribute1="some_value"
            [1] =>  attribute2="<h1 class=\"title\">Blahhhh</h1>"
        )

    [1] => Array
        (
            [0] => attribute1
            [1] =>  attribute2
        )

    [2] => Array
        (
            [0] => "
            [1] => "
        )

    [3] => Array
        (
            [0] => some_value
            [1] => <h1 class=\"title\">Blahhhh</h1>
        )
)

感谢您的选择。

1
请问您在这段代码中具体想要做什么? - anubhava
1个回答

1
你可以用 负回顾断言 来解决这个问题:
'/(.*?)\s*=\s*(\'|"|&#?\w+;)(.*?)(?<!\\\\)\2~/'
                                 ^^^^^^^^^

闭合引号不应该以\开头。给我:

Array
(
    [0] => Array
        (
            [0] => attribute1="some_value"
            [1] =>  attribute2="<h1 class=\"title\">Blahhhh</h1>"
        )

    [1] => Array
        (
            [0] => attribute1
            [1] =>  attribute2
        )

    [2] => Array
        (
            [0] => "
            [1] => "
        )

    [3] => Array
        (
            [0] => some_value
            [1] => <h1 class=\"title\">Blahhhh</h1>
        )
)

这个正则表达式并不完美,因为它使用了实体作为分隔符,就像引号一样,也可以用\进行转义。不知道这是否真的是有意为之。

还可以参考这个很棒的问题/答案:按分隔符拆分字符串,但如果被转义则不拆分


这个很好用,甚至包括 \n 字符。感谢 Hakre 提供的绝佳答案! - cmfolio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接