php - 用于匹配字符串中单引号单词并忽略转义单引号的正则表达式模式

标签 php regex preg-match

我的 PHP 代码如下所示:

$input = "City.name = 'New York'";
$literal_pattern = '/\'.[^\']*\'/';
preg_match($literal_pattern, $input, $token);
echo $token[0]; // prints 'New York'

我的正则表达式需要获取带有转义单引号的文字,例如:

$input = "City.name = 'New \' York'";
$literal_pattern = ???????????;
preg_match($literal_pattern, $input, $token);
echo $token[0]; // should prints 'New \' York'

$literal_pattern 的规则是什么?

最佳答案

没有这个条件,简单...

/('[^']*')/

...当然就足够了:匹配“单引号,后跟任意数量的非单引号符号,再后跟单引号”的所有序列。

但是因为我们需要在这里为两件事情做好准备——“正常”和“逃脱”。所以我们应该为我们的模式添加一些香料:

/('[^'\\]*(?:\\.[^'\\]*)*')/

它可能看起来很奇怪(确实如此),但它实际上也很简单:匹配...的序列

  • 单引号...
  • ...后跟零个或多个“正常”字符(不是'\),
  • ...后跟(“转义”符号,然后是零个或多个“正常”符号)的子表达式,重复 0 次或多次...
  • 后跟单引号。

例子:

$input   = "City.name = 'New \\' York (And Some Backslash Fun)\\\\'\\'"; 
# ...as \' in any string literal will be parsed as a _single_ quote

$pattern = "/('[^'\\\\]*(?:\\\\.[^'\\\\]*)*')/";
# ... a choice: escape either slashes or single quotes; I choose the former

preg_match($pattern, $input, $token);
echo $token[0]; // 'New \' York (And Some Backslash Fun)\\'

关于php - 用于匹配字符串中单引号单词并忽略转义单引号的正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13261250/

相关文章:

php - 从 eregi 到 preg_match

php - 使用 Apache 将 PHP 替换为 Python

php - Woocommerce Storefront template-tags.php 更改为 storefront_cart_link() 不可能

regex - 如何从 .htaccess 的正则表达式中的 url 捕获 %20?

.net - 使用正则表达式进行搜索和替换(包括lookbehinds)在 VS2017 中不起作用

php - 如何将可变模式与 preg_match 一起使用?

php - 是否可以检查数学表达式字符串?

php - 为什么这个 MySQL 查询需要永远运行?

第一次匹配时使用或使用第二个正则表达式的正则表达式?

PHP 正则表达式 : how to use newline in expression?