php 使用 preg_replace 仅替换第一个匹配项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6729710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:05:50  来源:igfitidea点击:

Replace only first match using preg_replace

phpregexpreg-replace

提问by deadbeef

I have a string with structure similar to: 'aba aaa cba sbd dga gad aaa cbz'. The string can be a bit different each time as it's from an external source.

我有一个结构类似于:的字符串'aba aaa cba sbd dga gad aaa cbz'。字符串每次都可能有点不同,因为它来自外部源。

I would like to replace only first occurrence of 'aaa'but not the others. Is it possible?

我只想替换第一次出现的'aaa'而不是其他的。是否可以?

回答by Paul

The optional fourth parameter of preg_replaceis limit:

preg_replace的可选第四个参数是limit

preg_replace($search, $replace, $subject, 1);

回答by codaddict

You can use the limitargument of preg_replacefor this and set it to 1so that at most one replacement happens:

您可以为此使用limit参数preg_replace并将其设置为,1以便最多发生一次替换:

$new = preg_replace('/aaa/','replacement',$input,1);

回答by T.Todua

for example, out $content is:

例如,out $content 是:

START 
FIRST AAA 
SECOND AAA

1) if you use:

1)如果你使用:

$content = preg_replace('/START(.*)AAA/', 'REPLACED_STRING', $content);

it will change everything from the START to the last AAA and Your result will be:

它将改变从 START 到最后一个 AAA 的所有内容,您的结果将是:

REPLACED_STRING

2) if you use:

2)如果你使用:

$content = preg_replace('/START(.*?)AAA/', 'REPLACED_STRING', $content);

Your Result will be like:

您的结果将类似于:

REPLACED_STRING 
SECOND AAA