Replace One In A String
<?php
$string = "An elephant is an elephant";
print str_replace('ph', 'php', $string);
print PHP_EOL;
print preg_replace('/ph/', 'php', $string);
print PHP_EOL;
print preg_replace('/ph/', 'php', $string, limit: 1);
print PHP_EOL;
$d = explode('ph', $string, 2);
print implode('php', $d);
str_replace() replaces every occurrence of a string by another one. What if you only want the first one replaced?
The easiest solution is to switch to preg_replace(): it works with a static regex, and by using the limit parameter.
A bit further is using explode() with its own limit, in collaboration with implode(). This is tricky.
Later, you may want to use strpos(), to locate the piece of string, and replace it.
Single characters changes may look into strtr().
And finally, what do you do if you need to replace one of the strings, at the nth position?
See Also
- Replacing the first one [Try me]
PHP Features
Last updated: 22 October 2026