Michael
Michael

Reputation: 44110

Remove backslashes from a string

I'm trying to replace \/ with / a string in PHP.

The string I have is:

http:\/\/xxx.xxx\/xxx

I want to replace the

\/

with just

/

(to give http://xxx.xxx/xxx).

All the escapes and stuff are confusing me!

I've tried every combination I can think of. I thought:

$str = preg_replace("\ \\ \/ /", "/ \/ /", $str);

would do the trick (removing the spaces) but no luck.

Upvotes: 1

Views: 105

Answers (5)

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

This task can be done with str_replace. Regular expression is used whenever it is useful not everywhere.

 $str= str_replace("\\", "", $str);

Test

$str="http:\/\/xxx.xxx\/xxx";
$str= str_replace("\\", "", $str);
echo $str;

Output

http://xxx.xxx/xxx

Edit

If you want to remove the back-slashes, you can also use stripslashes

$str="http:\/\/xxx.xxx\/xxx";
$str= stripslashes($str);
echo $str

Live Demo

Upvotes: 3

arychj
arychj

Reputation: 711

preg_replace() requires the first character to be your delimiter, also the backslash needs to be double escaped, once for the string, and once for the regex):

$str = preg_replace('#\\\\/#', '/', $str)

But as other users have suggested, it might be simpler to just use str_replace:

$str = str_replace('\/', '/', $str);

Upvotes: 3

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

You don't need a regex, you can just use str_replace :

$str = str_replace('\\', '', $str);

Upvotes: 6

Édouard Lopez
Édouard Lopez

Reputation: 43391

Regex add complexity, use a simple str_replace:

$str = str_replace('\/', '/', $str);

Test

$str="http:\/\/xxx.xxx\/xxx";
$str= str_replace("\/", "/", $str);
echo $str;

Output

http://xxx.xxx/xxx

Upvotes: 2

Masoud Aghaei
Masoud Aghaei

Reputation: 1221

this is a source of regex, I suggest you to check it . http://overapi.com/regex/

Upvotes: -2

Related Questions