ZomoXYZ
ZomoXYZ

Reputation: 1852

Why doesn't PHP's preg_replace function like escaping "\"?

I use the RegExr website to test my regular expressions. On that website it can easily find the character "\" with the RegEx string /\\/g. But when I use it in php it throws back:

Warning: preg_replace(): No ending delimiter '/'

My Code

$str = "0123456789 _+-.,!@#$%^&*();\/|<>";

echo preg_replace('/\\/', '', $str);

Why doesn't PHP like to escape "\"?

Upvotes: 1

Views: 36

Answers (1)

Thamilhan
Thamilhan

Reputation: 13293

When using it in the regexp use \\ to use it in the replacement, use \\\\ will turn into \\ that will be interpreted as a single backslash.

Use it like this:

<?php
$str = "0123456789 _+-.,!@#$%^&*();\/|<>";
echo preg_replace('/\\\\/', '', $str);

Output:

0123456789 _+-.,!@#$%^&*();/|<>

Upvotes: 1

Related Questions