Replace only first match using preg_replace

I have a line with a structure similar to: 'aba aaa cba sbd dga gad aaa cbz' . A string can be a little different each time because it is connected to an external source.

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

+42
php regex preg-replace
Jul 18 '11 at 7:17
source share
3 answers

The optional fourth preg_replace parameter is limit :

 preg_replace($search, $replace, $subject, 1); 
+83
Jul 18 '11 at 7:20
source share

You can use the limit preg_replace argument for this and set it to 1 so that no more than one replacement occurs:

 $new = preg_replace('/aaa/','replacement',$input,1); 
+8
Jul 18 '11 at 7:19
source share

e.g. from $ content:

 START FIRST AAA SECOND AAA 

1) if you use:

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

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

 REPLACED_STRING 

2) if you use:

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

Your result will look like this:

 REPLACED_STRING SECOND AAA 
0
Mar 27 '13 at 11:15
source share



All Articles