【问题标题】:Is it possible to use wildcard match with text? if yes how to find wildcard in text using PHP?是否可以对文本使用通配符匹配?如果是,如何使用 PHP 在文本中查找通配符?
【发布时间】:2014-10-20 00:15:38
【问题描述】:

我有以下字符串示例:

许多设备不需要维修,他们会尝试等等......

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

de*es

所以它会找到 "devices" 或其他通配符情况 喜欢

de*

d*v*s

这怎么能用 php 呢?

我尝试使用 fnmatch 函数,但它不起作用!

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

【问题讨论】:

  • 您只能将通配符与正则表达式一起使用 (preg_match())。
  • 如何使用 perg_match 做到这一点?
  • 如果您阅读 fmatch() 上的文档,您会发现它匹配文件名的方式与通配符在 shell 提示符下的匹配方式完全相同。你需要fnmatch("*de*es*", ...)
  • 您的建议对使用 fnmatch 非常有帮助

标签: php string search substring wildcard


【解决方案1】:

我使用了下面的代码,它适用于我,但我需要将(* 或空格)放在通配符的两端以使其适用于字符串搜索。

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";}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    相关资源
    最近更新 更多