php str_replace issue or bug?
-
21-09-2019 - |
Question
I have the following issue;
Here is my string I'm trying to remove javascript:l("
from the string below:
javascript:l("Bayou-La-Batre");
My code is;
$q_string = str_replace('javascript:l(" ','',$row['1']);
But it's failing.
This is quicker than a regex replace and quicker.
Any ideas?
Solution
You left a space
$q_string = str_replace('javascript:l("','',$row['1']);
OTHER TIPS
Change
$q_string = str_replace('javascript:l(" ','',$row['1']);
to
$q_string = str_replace('javascript:l("','',$row['1']);
Whenever I'm having this kind of problem, I try formatting my search/replace call in a monospaced editor to see if anything pops out
$q_string = str_replace('javascript:l(" ', '',
'javascript:l("Bayou-La-Batre")';
Formated like that, it becomes obvious that the 15th character of the search string does not match the 15th characters of the string that's being searched ([ ] vs. [B]).
Try removing that whitespace and you should be happy.
You can use
$q_string = substr($row['1'], 14);
to get the same results with some speed gain. I have tested speeds of three function so you can see how they compare with speed.
$string = 'javascript:l("Bayou-La-Batre")';
$str_replace = function($string) {
return str_replace('javascript:l("', '', $string);
};
print $str_replace($string) . "\n";
$substr = function($string) {
return substr($string, 14);
};
print $substr($string) . "\n";
$preg_replace = function($string) {
return preg_replace('/^[a-z:\(]+"/', '', $string);
};
print $preg_replace($string) . "\n";
function measure($function, $string) {
$start = microtime(true);
for($i = 0; $i < 1000000; $i++) {
$function($string);
}
return microtime(true) - $start;
}
print 'Substr: ' . measure($substr, $string) . "\n";
print 'Str replace:' . measure($str_replace, $string) . "\n";
print 'Preg replace:' . measure($preg_replace, $string);
The output of this on my machine
Bayou-La-Batre")
Bayou-La-Batre")
Bayou-La-Batre")
Substr: 3.7492098808289
Str replace:4.5258920192719
Preg replace:5.8815109729767