[英]preg_match() fails with string containing slashes
I have a function like this:我有一个这样的 function:
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.除非
$row['name']
包含类似blah / blah / something
的东西,否则它会起作用,在这种情况下,它会说它无法在数组中找到它,即使它存在。
How do I fix this?我该如何解决?
This is because the slash in your input: blah / blah / something
is seen as delimiter for the regex. 这是因为输入中的斜杠:
blah / blah / something
被视为正则表达式的分隔符。
To solve this you can escape your input with preg_quote()
, eg 为了解决这个问题,您可以使用
preg_quote()
转义您的输入,例如
function in_array_r($item , $array){
return preg_match('/"'.
preg_quote($item, "/") .'"/i' , json_encode($array));
}
I know this in an old question, but I wanted to share that I resolved this, simply by using a different delimiter, eg我在一个老问题中知道这一点,但我想分享一下我解决了这个问题,只需使用不同的定界符,例如
$var = 'string with /// slashes';
preg_match("~.*?$var.*?~i", $string);
This is a perfectly valid syntax in PHP.这是 PHP 中完全有效的语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.