问题
I have a function like this:
function in_array_r($item , $array){
return preg_match('/"'.$item.'"/i' , json_encode($array));
}
and then I use it like:
if(in_array_r($row['name'], $items_array)){
// something..
}
It works unless the $row['name']
contains something like blah / blah / something
, in which case it says that it can't find it in the array, even though it exists.
How do I fix this?
回答1:
This is because the slash in your input: blah / blah / something
is seen as delimiter for the regex.
To solve this you can escape your input with preg_quote(), e.g.
function in_array_r($item , $array){
return preg_match('/"'. preg_quote($item, "/") .'"/i' , json_encode($array));
}
来源:https://stackoverflow.com/questions/34666498/preg-match-fails-with-string-containing-slashes