当匹配字符串时,正则表达式如何忽略转义引号?

前端之家收集整理的这篇文章主要介绍了当匹配字符串时,正则表达式如何忽略转义引号?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试编写一个匹配所有内容的正则表达式但是没有被转义的撇号.考虑以下: @H_404_7@

@H_404_7@

<?PHP $s = 'Hi everyone,we\'re ready now.'; ?>
@H_404_7@我的目标是编写一个基本匹配字符串部分的正则表达式.我在考虑像

@H_404_7@

/.*'([^']).*/
@H_404_7@为了匹配一个简单的字符串,但我一直试图弄清楚如何在撇号上得到负面的lookbehind,以确保它没有反斜杠……

@H_404_7@有任何想法吗?

@H_404_7@ – JMT

解决方法

<?PHP
$backslash = '\\';

$pattern = <<< PATTERN
#(["'])(?:{$backslash}{$backslash}?+.)*?{$backslash}1#
PATTERN;

foreach(array(
    "<?PHP \$s = 'Hi everyone,we\\'re ready now.'; ?>",'<?PHP $s = "Hi everyone,we\\"re ready now."; ?>',"xyz'a\\'bc\\d'123","x = 'My string ends with with a backslash\\\\';"
    ) as $subject) {
        preg_match($pattern,$subject,$matches);
        echo $subject,' => ',$matches[0],"\n\n";
}
@H_404_7@版画

@H_404_7@

<?PHP $s = 'Hi everyone,we\'re ready now.'; ?> => 'Hi everyone,we\'re ready now.'

<?PHP $s = "Hi everyone,we\"re ready now."; ?> => "Hi everyone,we\"re ready now."

xyz'a\'bc\d'123 => 'a\'bc\d'

x = 'My string ends with with a backslash\\'; => 'My string ends with with a backslash\\'

猜你在找的正则表达式相关文章