是否可以使用通配符与文本匹配?如果是,如何使用PHP在文本中找到通配符?

时间:2014-08-26 15:34:08

标签: php string search substring wildcard

我有以下字符串示例:

  
    

许多设备不需要修理它们等等......

  

我想查找子字符串是否在此文本中,但使用通配符,如下例所示:

de * es

因此它会找到"设备" 或其他通配符案例 像

DE *

d * V * S

这怎么用ph​​p?

我试图使用fnmatch功能,但它不起作用!

$txt="many kinds of devices not need repair them and they try etc....";
if (fnmatch("de*es",$text)) { echo "found";} else {exit;}

1 个答案:

答案 0 :(得分:0)

我使用下面的代码并且它可以和我一起使用,但是我需要在通配符的两端放置(*或空格)以使其在字符串中搜索。

function wildcardcheck( $wildcard, $orginal_text) 
{
    $regex = str_replace(array("\*", "\?"), array('.*','.'), preg_quote($wildcard));
    return preg_match('/^'.$regex.'$/is', $orginal_text);
}

$text="many kinds of devices not need repair them and they try etc...";
$word="de*es*";
if(ltrim($word,'*')==$word) $word=' '.$word; else $word=ltrim($word,'*');
if(rtrim($word,'*')==$word) $word=$word.' '; else $word=rtrim($word,'*');

if (wildcardcheck($word,$text)) { echo "found";} else {echo "not found";}