使用 preg_match_all 查找带转义撇号的字符串

Using preg_match_all to find a string with an escaped apostrophe

我正在尝试 preg_match_all 我从用户输入中获得的字符串,其中有一个撇号。首先,我在常规字符串上对其进行了测试,看它是否匹配,确实如此。但是,当我尝试在同一个用户输入字符串上对其进行测试时,它不起作用。我认为这是因为在我比较它们之前,用户输入中的撇号被转义了。

$temp1 = "I'm a person.";

preg_match_all('/I\'m\s+(.+)/i', $temp1, $matches);
$temp1 = $matches[1][0];
echo $temp1;

输出 : 一个人。

但是,由于我从用户输入中获取 $temp 并转义了撇号,因此它在取出时转义了撇号,因此它不匹配:

$temp2 = "I\'m a person.";

preg_match_all('/I\'m\s+(.+)/i', $temp2, $matches);
$temp2 = $matches[1][0];
echo $temp2;

输出 : null.

我该如何解决这个问题?谢谢

您可以使用:

preg_match_all('/I\\\'m\s+(.+)/i', $temp2, $matches);
echo $matches[1][0];

输出:

a person.

使用 \\ 匹配输入中的单个反斜杠。