PHP replace only first occurrence of a string match.

Bookmark and Share

How to replace only the first occurrence of a string in php.

Say you wanted to only replace the first occurrence of a string match instead of all occurrences You would use php preg_replace function to do the trick.

The code is below:

<?
$var = 'abcdef abcdef abcdef';
// pattern, replacement, string, limit
echo preg_replace('/abc/', '123', $var, 1); // outputs '123def abcdef abcdef'
?>

Just incase you wanted to still match all occurrences, just use the php function erag_replace.
The code is below:


<?
$var = 'abcdef abcdef abcdef';
// pattern, replacement, string
echo ereg_replace('abc', '123', $var); // outputs '123def 123def 123def'
?>

Please rate this post by clicking a star:

(18 votes, average: 5.00 out of 5)

One Response to “PHP replace only first occurrence of a string match.”

  • Nice. So simple, but way more useful then trying to figure out string positions in order to isolate only the first. Thanks for the tip.

Leave a Reply





Tags: , , , , , , , ,