Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有PHP preg_replace()的正则表达式需要在字符串中找到最近的名称_Php_Regex_Preg Replace - Fatal编程技术网

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

带有PHP preg_replace()的正则表达式需要在字符串中找到最近的名称,php,regex,preg-replace,Php,Regex,Preg Replace,我需要在字符串中找到最接近的名称,我该怎么做 我得到的最接近的是合适的,它发现离字符串最远的是: $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,

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

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

$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 -->
$string=“乔、鲍勃、路易斯、桑乔、鲍勃、马可、卢拉、汉娜、鲍勃、马可、路易斯”;
$new_string=preg_replace('/(bob(?!bob))/','found it!',$string);
echo$new_字符串;
我该怎么做呢?并有如下输出:

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

您使用的正则表达式
(bob(?。*bob))
匹配一行中最后出现的
bob
(不是一个完整的单词),因为
匹配除换行符以外的任何字符,并且负向前看确保
bob
之后没有
bob
。请参阅(如果我们使用
preg\u替换
默认选项)

你可以用

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

regex
\bbob\b
将匹配整个单词,并且使用
limit
参数将仅匹配单词“bob”的第一次出现

见:

限制
每个主题字符串中每个模式的最大可能替换。默认值为
-1
(无限制)


你可以试着做一个消极的回顾,就像这样

$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 -->
$string=“乔、鲍勃、路易斯、桑乔、鲍勃、马可、卢拉、汉娜、鲍勃、马可、路易斯”;

$new_string=preg_replace('/(?尝试使用preg_replace的第四个参数(
limit
)等于1Lookarounds是此任务不必要的开销。Wiktor的答案是最佳选择。