pheromix
pheromix

Reputation: 19347

How to replace only once a find string?

For example there is a string :

$valeur = "a-b-c-b-d-e";

The letter "b" is present twice in this. I want to replace only the first "b".

How to do that ? I used str_replace but it replaces all occurences.

Upvotes: 0

Views: 121

Answers (2)

Er. Anurag Jain
Er. Anurag Jain

Reputation: 1793

You cab try preg_replace here.

    $valeur = "a-b-c-b-d-e";
    echo preg_replace('/b/', 'x', $valeur, 1); // outputs 'a-x-c-b-d-e'

Here 4th parameter is for limit and this is optional.

thanks

Upvotes: 0

Darragh Enright
Darragh Enright

Reputation: 14136

You can use preg_replace and set a limit like so:

$valeur = "a-b-c-b-d-e";
$replacement = '#';

echo preg_replace('/b/', $replacement, $valeur, 1); // a-#-c-b-d-e

You didn't mention what you wanted to replace it with so I'm adding # as a placeholder.

Upvotes: 3

Related Questions