Home > Back-end >  How to check if a string have multiple characters Next to each other with PHP?
How to check if a string have multiple characters Next to each other with PHP?

Time:02-24

I want to check string have | | or not:

                 if(preg_match("/|  |/", $res)) {
                    echo str_replace("|  |", "\n", $res);
                 } else {
                    echo $res;
                 }

but with preg_match it is not working. how should I check it?

CodePudding user response:

You should enscape and | \|\ \ \|, but better to use str_contains.

var_dump(str_contains($res, '|  |'));

But in this case, you do not need the condition str_replace is sufficient. If the string not contains | | then nothing will happen.

echo str_replace("|  |", "\n", $res);

CodePudding user response:

The | and characters are special characters in a regex and need to be escaped.

Changing | | to \|\ \ \| should do the trick.

  •  Tags:  
  • php
  • Related