How to Replace Only the First Occurrence of a String in PHP?

There are several ways in PHP that you could use to replace only the first match in a string. In this article, we've handpicked a few that we believe are good for the job.

For all the examples in this article, we'll be using the following string to replace the first occurrence of foo:

$str = 'foobar foobaz fooqux';

Can I Use str_replace() to Replace Only the First Match?

By default, PHP's str_replace(), replaces all occurrences of a match; an optional fourth argument to the function gives the number of replacements performed, and does not help in limiting the number of replacements that will be made. Therefore, it may not be helpful in restricting the number of replacements to only the first find.

#Using preg_replace()

The fourth argument to the preg_replace() function can be used to limit the number of times the match is replaced. For example, to limit it to only the first match, you could do the following:

$replaceWith = '';
$findStr = 'foo';

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

// output: "bar foobaz fooqux"

Replacing First Match From Multiple Patterns Using preg_replace():

The first argument to the preg_replace() function can either be a string pattern or an array of string patterns. If an array of patterns is provided then to replace the first match of each pattern you can do the following:

$replaceWith = '';

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

// output: "bar foo fooqux"

#Using substr_replace()

The substr_replace() function has the following syntax:

// PHP 4+
substr_replace($string, $replacement, $startOffset, $length);

The last two parameters of the substr_replace() function (i.e. the starting offset of the match and the length of the portion of string which is to be replaced) can be used to ensure only the whole string (that's of concern to us) is replaced, and only once. Consider the following example:

$replaceWith = '';

$findStr = 'foo';
$pos = strpos($str, $findStr);

if ($pos !== false) {
    $str = substr_replace($str, $replaceWith, $pos, strlen($findStr));
}

echo $str;

// output: "bar foobaz fooqux"

#Using implode() and explode()

Using the third argument to the explode() function, you can ensure you only split the string once at the first match. Consider the following (complete) syntax of the explode() function:

// PHP 4+
explode($separator, $str, $limit);

When a positive value is supplied as the $limit, the returned array will contain a maximum of $limit elements with the last element containing the rest of string. For example, if limit is set to 2, then the returned array will contain ONE matching element with the last element containing the rest of the string.

With that knowledge, consider the example below:

$replaceWith = '';
$findStr = 'foo';

print_r(explode($findStr, $str, 2));

// output: Array ([0] => "" [1] => "bar foobaz fooqux")

Now with that result, you can simply use implode() to join the string back using the replace-with value like so:

$replaceWith = '';
$findStr = 'foo';

echo implode($replaceWith, explode($findStr, $str, 2));

// output: "bar foobaz fooqux"

This post was published (and was last revised ) 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.