How to preg_replace() First Match Only in PHP?

Find out how to replace only the first match with preg_replace() in PHP

The preg_replace() function has an optional fourth argument; a number that can be used to limit the number of replaces that are made based on the regular expression pattern. It has the following syntax:

// PHP 4+
preg_replace($pattern, $replacement, $string, $limit);

The limit parameter defaults to -1 which means no limit. In order to only replace the first occurrence of the string you can do the following:

$str = 'foobar foobaz fooqux';
$replaceWith = '';
$findStr = 'foo';

echo preg_replace('/' . $findStr . '/', $replaceWith, $str, 1);

// output: "bar foobaz fooqux"

This is also works when you have an array of string patterns:

$str = 'foobar foobaz fooqux';
$replaceWith = '';

echo preg_replace(['/foo/', '/baz/'], $replaceWith, $str, 1);

// output: "bar foo fooqux"

Hope you found this post useful. It was published . Please show your love and support by sharing this post.