Replace several occurences in one string

$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

something like…
preg_replace(‘/[toB]{2,}/’,‘b’,$string);

Close :wink:

start with the string you want to find
[toB]
remember that [ & ] must be escaped with \
\[toB\]
put this into a search group
[ \[toB\] ]
add that you want to group one or more times +
[\[toB\]]+

/[\\[toB\\]]+/

preg_replace('/[\\[toB\\]]+/', 'b', $string)

Thanks, the problem is if I have a [toA] in the middle it does not work.
Need to bee a regex exactly for [toB]

$string = “123-[toB][toB][toB]-567-[toB]-78-[toB][toB][toA]”;

Sorry my mistake


preg_replace('/(\\[toB\\])+/', 'b', $string)

went square bracket crazy

@Mod … can you edit my description above and change the two ouside square brackets for normals

Many thanks! Worked.