2016-01-20 39 views
0

我有一个比较两个字符串的函数工作。除非字符串包含斜线/,否则它可以很好地工作。我能做些什么来解决这个问题?的preg_match功能无法用斜杠

function in_array_r($item , $array){ 
    return preg_match('/"'. preg_quote($item, "/") .'"/i' , json_encode($array)); 
} 

我运行它像:

if(in_array_r($row['name'], $products)){ 
    // 
} 

所以silverware with golden spoon new作品而silverware with golden spoon/new不能使用,即使它存在于两个数组斜线的感觉。

+0

你有倾倒的正则表达式,并看着它? –

+0

感谢您的回复!你的意思是比较两个数组?两者的内容几乎相同。我看过他们。 – user1996496

+0

不,我的意思是'preg_quote'的返回值。您需要确保它包含预期值。还转储json编码数组。访问然后regex101.com并使用两者来验证正则表达式正在工作 –

回答

0

也许你必须使用转义字符是这样的:

silverware with golden spoon \/ new 

这将跳过\符号之后的任何字符。

0

我会结合使用两件事来解决你的问题。首先,如果你知道你的数据会经常出现斜杠,你应该选择一个不同的分隔符。我通常使用代字符而不是正斜杠,因为我解析了很多URL,并且厌倦了不必担心在所有时间都逃脱它们。

我会做的第二件事是使用JSON_UNESCAPED_SLASHES标志与json_encode。下面是我的意思的例子:

<?php 

$products = array('silverware with golden spoon new', 'silverware with golden spoon/new'); 

$item = 'silverware with golden spoon/new'; 

function in_array_r($item , $array){ 
    return preg_match('~"'.$item.'"~i', json_encode($array, JSON_UNESCAPED_SLASHES)); 
} 


if(in_array_r($item, $products)){ 
    print "Match found!"; 
} 
else { 
    print "No match was found."; 
} 

这将输出:

Match found! 

这里是一个工作演示:

http://ideone.com/BLEsIy