| ||||||
|
Setting preg_replace() limit to only replace the first or a specified number of matches
If you are performing a preg_replace on a string it might well be that you do not mean to replace every match within it. Instead you might only want to replace the first item, or a specific number of items. Accomplishing this task is easy. The last parameter of preg_replace() defines the function's limit: preg_replace($regex, $replace, $string, $limit); Therefore, if we set the limit to one in the following example, we will end up with the string Manchester United is better than Manchester City: <?php $string = "Manchester City is better than Manchester City"; $replacement = "United"; $string = preg_replace('(City)', $replacement, $string, 1); echo $string; ?> While the code above only changed the first City, the code below will change Man United and Man City to Manchester United and Manchester City: <?php $string = "Man United is better than Man City"; $replacement = "Manchester"; $string = preg_replace('(Man)', $replacement, $string, 2); echo $string; ?>
|