iqbal_cs iqbal_cs - 4 years ago 191
PHP Question

preg_replace not working as expected replacing backslashes?

I was using the delimiters described in this answer:

Here is shell php I'm using to demonstrate the problem:

php cli

I'm using a function on a web project that replaces a namespace syntax for a path, eg:


should be converted to:


But I tried many ways, some threw the following warning:

Warning: preg_replace(): No ending delimiter '/' found in...

Which I don't want to show.

The warning above shows when using this as regex:

extra: (please look at the image) why it shows a bad encoded string?

UPDATE: why does it not work as this PHP Live Regex ?

Answer Source
  1. You need to use "/\\\\/" instead of "/\\/" because \\ will produce \ (a single backslash) in a PHP string literal.


  2. Why are you using regular expressions for such simple case? Stick to str_replace() or strtr():

    echo strtr($str, ['\\' => '/']);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download