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"
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.