简体   繁体   中英

Matching full text from string with php regular expression

Lets say I have sentence like this: "Hello world this is a test". In this sentence I want to match with "world test" or "hell this" something like that. How can I do this with preg_match? This is probably something like mysql fulltext search.

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

You can use \\b for defining boundaries as

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

Explanation

  1. \\b assert position at a word boundary
  2. (world\\stest|hell\\sthis) this'll check for world test or hell this
<?php
$str = "Hello world this is a test";
$src1 = 
$src1 = str_replace(' ','.*',$src1);
preg_match("/(.*$src1.*)/i", $str, $results);

print_r($results);
?>

I have tried this, and looks like its working for me:

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

Many thanks for your help.

You should combine two expressions: world.*test and hell.*this . Resulting expression is world.*test|hell.*this . (FIY .* matches any number of any character).

PS: You can also consider using CleanRegex :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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