Question

I have

$string="this+++is+test";

Need with str_replace change many "pluses" for one "plus";

example: this+is+test

Was it helpful?

Solution 4

This solution assumes you don't have "+"s at the ends of your string. Since you don't in your example, I assume that's OK.

php > $string="this+++is+test";
php > echo implode('+', # reassemble the string on a single '+' sign
        array_filter( # strip empty-string parts of the array entirely
          explode('+', $string) # Split the string into array on '+'
        )
      );
this+is+test

OTHER TIPS

Use preg_replace instead of str_replace for this time.

$string="this+++is+test";
$string = preg_replace("/[+]+/", "+", $string);

Here [+]+ means the + sign to be 1 or more time consecutively.

Use this regex

\++

The above regex matches + any time.

And replace it with

+

And since we are replacing it with +, there is no probs.

Replace 2 or more + with +:

$str = "this+++is+test";

$str = preg_replace('/\+{2,}/', "+", $str);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top