繁体   English   中英

用php正则表达式匹配字符串中的全文

[英]Matching full text from string with php regular expression

可以说我这样说:“你好,这是一个考验”。 在这句话中,我想与“世界测试”或“听到这个”相匹配。 我该如何使用preg_match? 这可能类似于mysql全文搜索。

$str = "Hello world this is a test";
$src1 = "world test";
$src1 = "hell this";

您可以使用\\b将边界定义为

/\b(world\stest|hell\sthis)/

说明

  1. \\b在单词边界处断言位置
  2. (world\\stest|hell\\sthis)这将检查world testhell this
<?php
$str = "Hello world this is a test";
$src1 = 
$src1 = str_replace(' ','.*',$src1);
preg_match("/(.*$src1.*)/i", $str, $results);

print_r($results);
?>

我已经尝试过了,看起来它对我有用:

$searchword = str_replace(" ", "|", $src1);
preg_match_all("/$searchword/i", $str)

非常感谢您的帮助。

您应该结合两个表达式: world.*testhell.*this 结果表达式是world.*test|hell.*this (FIY .*匹配任意数量的任何字符)。

PS:您也可以考虑使用CleanRegex

$str = "Hello world this is a test";

if (pattern('world.*test|hell.*this')->matches($str)) 
{
    // Matched! :)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM