preg_match确定相似的模式

时间:2019-01-19 04:37:56

标签: php regex preg-match

classList

上面的代码很好用,但是如果放

$lines ="Where to find train station";
$pattern = "/Where ([^\s]+) find train station/i";

preg_match($pattern, $lines, $matches);
var_dump($matches);

这不起作用。如何解决这样的问题?也可以使用这个词吗?

$lines ="Where can I find train station";

即使在一个或多个单词之间的情况下,任何人都可以建议如何检测相似的模式。

提前谢谢

1 个答案:

答案 0 :(得分:0)

尝试(.*?)来匹配并捕获wherefind train station之间的任意字符。

.匹配任何字符,而*?lazy quantifier,消耗与匹配模式所需的字符一样少的字符。

这是一个可行的示例:

$pattern = "/Where (.*?) find train station/i";

$tests = [
    "Where to find train station",
    "Where can I find train station",
    "Where can i and you and me find train station"
];

foreach ($tests as $test) {
    preg_match($pattern, $test, $matches);
    var_dump($matches);
}

输出:

array(2) {
  [0]=>
  string(27) "Where to find train station"
  [1]=>
  string(2) "to"
}
array(2) {
  [0]=>
  string(30) "Where can I find train station"
  [1]=>
  string(5) "can I"
}
array(2) {
  [0]=>
  string(45) "Where can i and you and me find train station"
  [1]=>
  string(20) "can i and you and me"
}

Try it!