如何使用 PHP 检查 RegEx 搜索模式的前导字符?

How to check preceding character of a RegEx search pattern using PHP?

我想检查 search pattern 的前一个字符是否是字母数字字符。

如果为真,什么也不做。

如果fasle,去掉search pattern中前面的space

例如:

$string1 = "This is a test XYZ something else";

$string2 = "This is a test? XYZ something else";

$pattern = " XYZ";

在$string1场景下,搜索模式的前导字符为t,视为匹配,不执行任何操作。

在 $string2 场景中,搜索模式的前导字符是 ? 并被认为是不匹配的,我正在删除 searhc pattern 中多余的 space。

成功:

$string2 = "This is a test?XYZ something else";

如何在 PHP 中完成?

您可以使用 \B XYZ 模式并使用 preg_replace_callbacktrim 匹配值并将其插入:

$string1 = "This is a test XYZ something else";
$string2 = "This is a test? XYZ something else";
$pattern = " XYZ";
echo preg_replace_callback('~\B'.$pattern.'~', function($m) { return trim($m[0]); }, $string1) . PHP_EOL;
// => This is a test XYZ something else
echo preg_replace_callback('~\B'.$pattern.'~', function($m) { return trim($m[0]); }, $string2);
// => This is a test?XYZ something else

PHP demo

由于 \B 在与单词边界(非单词边界)匹配的位置以外的位置匹配,因此模式 \B XYZ 将仅在非单词字符之后匹配。

更多详情:您的模式以 space 开头。这是一个非字字符。通过在它之前添加 \B 我们要求 space 之前的字符也应该是一个非单词字符。否则,我们将无法匹配。单词 char 是 [a-zA-Z0-9_] 范围内的一个字符。如果您需要自定义边界,请使用类似 (?<![a-zA-Z0-9]) 的 lookbehind 从边界字符中排除下划线。

有关非词边界的详细信息,请参阅this What are non-word boundary in regex (\B), compared to word-boundary? SO thread