preg_match() 失败,字符串包含斜线 [英] preg_match() fails with string containing slashes
本文介绍了preg_match() 失败,字符串包含斜线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的功能:
function in_array_r($item , $array){
return preg_match('/"'.$item.'"/i' , json_encode($array));
}
然后我像这样使用它:
if(in_array_r($row['name'], $items_array)){
// something..
}
除非$row['name']
包含类似blah/blah/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?
推荐答案
这是因为输入中的斜线:blah/blah/something
被视为正则表达式的分隔符.
This is because the slash in your input: blah / blah / something
is seen as delimiter for the regex.
要解决这个问题,您可以使用 preg_quote()
,例如
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));
}
这篇关于preg_match() 失败,字符串包含斜线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文