PHP preg_replace() 的正则表达式需要在字符串中找到最近的名称

Regex with PHP preg_replace() need to find the nearest name in string

我需要在字符串中找到最接近的名称我该怎么做?

我得到的最接近的是适当的,它发现离字符串最远的是:

$string = "joe,bob,luis,sancho,bob,marco,lura,hannah,bob,marco,luis";

$new_string = preg_replace('/(bob(?!.*bob))/', 'found it!', $string);

echo $new_string;
<!-- outputs: joe,bob,luis,sancho,bob,marco,lura,hannah,found it!,marco,luis -->

我该怎么做才合适?并有这样的输出:

<!-- outputs: joe,found it!,luis,sancho,bob,marco,lura,hannah,bob,marco,luis -->

您使用的正则表达式 (bob(?!.*bob)) 匹配一行中最后一次出现的 bob(不是整个单词),因为 . 匹配除换行符以外的任何字符,负前瞻确保 bob 之后没有 bob。请参阅 what your regex matches(如果我们使用具有默认选项的 preg_replace)。

您可以使用

$re = '/\bbob\b/'; 
$str = "joe,bob,luis,sancho,bob,marco,lura,hannah,bob,marco,luis"; 
$result = preg_replace($re, 'found it!', $str, 1);

IDEONE demo

正则表达式 \bbob\b 将匹配整个单词,使用 limit 参数将仅匹配单词 'bob'.

的第一次出现

参见preg_replace help

limit
The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

你可以试试消极的回顾,就像这样

$string = "joe,bob,luis,sancho,bob,marco,lura,hannah,bob,marco,luis";

$new_string = preg_replace('/((?<!bob)bob)/', 'found it!', $string, 1);

echo $new_string;
<!-- outputs: joe,found it!,luis,sancho,bob,marco,lura,hannah,bob,marco,luisoff -->

正如 Wiktor 所说,使用限制选项只匹配名字的第一次出现。