Replace several instances to a char in string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pedroz
Forum Commoner
Posts: 99
Joined: Thu Nov 03, 2005 6:21 am

Replace several instances to a char in string

Post by pedroz »

$string = "123-[toB][toB][toB]-567-[toB]-78-[toB][toB]";
// should echo 123-b-567-b-78-b

How can I replace the [toB] into a letter b even it is repeated?

str_replace('[toB]','b', $string);
gives me 123-bbb-567-b-78-bb

but need // 123-b-567-b-78-b
pedroz
Forum Commoner
Posts: 99
Joined: Thu Nov 03, 2005 6:21 am

Re: Replace several instances to a char in string

Post by pedroz »

something like..
preg_replace('/[toB]{2,}/','b',$string);
Post Reply