[英]check a string contains any word from array
i have a set of predefined array contains strings and words.I am trying to check whether my string contains at least one word from that array.我有一组包含字符串和单词的预定义数组。我正在尝试检查我的字符串是否至少包含该数组中的一个单词。
$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code testy';//code is already in that array
i tried many ways,but not correct solution我尝试了很多方法,但没有正确的解决方案
first method
$i = count(array_intersect($array, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $string))));
echo ($i) ? "found ($i)" : "not found";
second method
if (stripos(json_encode($array),$string) !== false) { echo "found";}
else{ echo "not found";}
I suppose you are looking for a match which is any of the words.我想你正在寻找一个匹配的词。
$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code|testy';
foreach ($array as $item ) {
if(preg_match("/\b{$string}\b/i", $item)) {
var_dump( $item );
}
}
You have to iterate over the array and test each one of the cases separately, first 'code', then 'testy', or whatever you want.您必须遍历数组并分别测试每个案例,首先是“代码”,然后是“testy”,或者您想要的任何内容。 If you json_encode, even if you trim both of strings to do this comparaison, the return will be not found.如果你json_encode,即使你修剪两个字符串来做这个比较,也不会找到返回。
But in the first string if you had like this但是在第一个字符串中,如果你有这样的
$array = array("PHP code testy Sandbox Online","abcd","defg" );
$string = 'code testy';//code is already in that array
you will get surely a "found" as return.你肯定会得到一个“发现”作为回报。
if (stripos(trim(json_encode($array)),trim($string)) !== false) { echo "found";}
else{ echo "not found";}
You could use explode()
to get an array from the strings and then go through each of them.您可以使用explode()
从字符串中获取一个数组,然后遍历它们中的每一个。
$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code testy';
foreach(explode(' ', $string) as $key => $value) {
foreach($array as $arrKey => $arrVal) {
foreach(explode(' ', $arrVal) as $key => $str) {
if ($value == $str) {
echo $str . ' is in array';
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.