user3518675
user3518675

Reputation: 115

php how to escape a string for preg_match?

I'am trying to pass a string

  preg_replace('/'.preg_quote($my_str).'/i', '', $string);

but I get an error

preg_replace(): Unknown modifier '\'

is there any other solutions to escape those backslashes?

Upvotes: 1

Views: 4039

Answers (2)

Nambi
Nambi

Reputation: 12042

Pass the delimiter to the second argument of the preg_quote

echo preg_replace('/'.preg_quote("$my_str",'~').'/i', '',$string );
                                            ^

Upvotes: 1

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

Your $my_str contains / character in it which you are using as regex delimiter. So you have two solutions,

One, replace the delimiter / into anything else which doesn't contain in the variable. For example ~

preg_replace('~'.preg_quote($my_str).'~i', '', $string);
              ^                       ^

Second solution, replace all the / with \/ from $my_str after preg_quote

$my_str = str_replace('/', '\/', preg_quote($my_str));
$some_str = preg_replace('/'.$my_str.'/i', '', $string);

Upvotes: 0

Related Questions