How to replace only the first occurrence of a substring in PHP? (str_replace for first match)
Hello everyone! I'm writing in PHP and encountered an unexpected problem. I have a string where I need to replace only the first occurrence of a specific substring, leaving all others untouched.
Here's an example. Let's say I have some HTML code or just text:
```php
$text = "Apple, banana, apple, orange, apple";
$search = "apple";
$replace = "pear";
```
I want the result to be: "Apple, banana, pear, orange, apple" — meaning only the second occurrence is replaced (the first case-sensitive one, but that's not important). Or, if I want to replace exactly the first occurrence, to get "pear, banana, apple, orange, apple".
The problem is that the standard `str_replace()` function replaces ALL occurrences. I tried `str_replace($search, $replace, $text)`, but it replaces every "apple"
No answers yet.
Log in to leave an answer
Blogs