preg_match() fails with string containing slashes

こ雲淡風輕ζ 提交于 2019-12-20 05:38:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!