TroodoN-Mike
TroodoN-Mike

Reputation: 16175

preg_replace - regular expression php for two different characters

Is this a correct syntax for preg_replace (regular expression) to remove ?ajax=true or &ajax=true from a string?

echo preg_replace('/(\?|&)ajax=true/', '', $string);

So for example /hello/hi?ajax=true will give me /hello/hi and /hello/hi?ajax=true will give me /hello/hi

Do I need to escape &?

Upvotes: -1

Views: 204

Answers (2)

stema
stema

Reputation: 92986

Why don't you try it?

You don't need to escape "&". It is not a special character in regex.

Your expression should be working, that is an alternation that you are using. But if you have only single characters in your alternation, it is more readable, if you use a character class.

echo preg_replace('/[?&]ajax=true/', '', $string);

[?&] is a character class, it will match one character out of the characters listed between the square brackets.

Upvotes: 1

Lo Juego
Lo Juego

Reputation: 1325

I think it is ok your expression. You can add (?i) to ignore Upper Case letters. The result should be something like:

echo preg_replace('/(\?|&)(?i)ajax=true/', '', $string);

Upvotes: 0

Related Questions