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:



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.
What if I want to bold the first occurrence of a word in a description? I tried using:
<?
// $description holds the entire description
ereg_replace($keyword, '‘.$keyword.’‘, $description);
?>
And I get an error: “Warning: Wrong parameter count for ereg_replace()”
Looks like it actually bolded on your website… odd… I got rid of the 1 at the end of the parameters and it works. Does this only work with an old version of PHP or something?
Worked like a charm! Thanks a lot man – comes in handy all the time when playing with WordPress content.
I am using a replace function so I can create an unordered list. Problem is I need to ignore the first occurance because I start my list and then use the replace to close and start the lists.
Thankfully, I found your post to help me replace the first occurance of a match in the string! Worked just like I needed it to!