Frankie
Frankie

Reputation: 611

Matching Regular Expression in Javascript and PHP problem

I can't figure out how to get the same result from my Javascript as I do from my PHP. In particular, Javascript always leaves out the backslashes. Please ignore the random forward and backslashes; I put them there so that I can cover my basis on a windows system or any other system. Output:

Input String: "/root\wp-cont  ent\@*%'i@$@%$&^(@#@''mage6.jpg:"    
/root\wp-content\image6.jpg (PHP Output)
/rootwp-contentimage6.jpg (Javascript Output)

I would appreciate any help!

PHP:
<?php
$path ="/root\wp-cont  ent\@*%'i@$@%$&^(@#@''mage6.jpg:";
 $path = preg_replace("/[^a-zA-Z0-9\\\\\/\.-]/", "", $path);
 echo $path;
?>

Javascript:
<script type="text/javascript">
var path = "/root\wp-cont  ent\@*%'i@$@%$&^(@#@''mage6.jpg:"; //exact same string as PHP
var regx = /[^a-zA-Z0-9\.\/-]/g;
path = path.replace(regx,"");
document.write("<br>"+path);
</script>

Upvotes: 0

Views: 153

Answers (2)

gX.
gX.

Reputation: 952

Yup, Qtax is correct, then you can use this:
var regx = /[^a-zA-Z0-9\.\/-\\]/g;

Upvotes: 0

Qtax
Qtax

Reputation: 33908

Your problem is that you're not escaping the backslashes in your JS string, which you should always do (even in PHP) if you mean a backslash.

Example:

var path = "/root\wp-cont  ent\@*%'i@$@%$&^(@#@''mage6.jpg:";
alert(path);
path = "/root\\wp-cont  ent\\@*%'i@$@%$&^(@#@''mage6.jpg:";
alert(path);

Upvotes: 3

Related Questions