preg_match для определения похожего паттерна - PullRequest
0 голосов
/ 19 января 2019
$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";

, это не работает.Как решить эту проблему?Возможно ли работать и с этим словом?

$lines ="Where can i and you and me find train station";

Может кто-нибудь подсказать, как обнаружить похожий паттерн даже между одним или несколькими словами.

Заранее спасибо

1 Ответ

0 голосов
/ 19 января 2019

Попробуйте (.*?) для сопоставления и захвата произвольных символов от where до find train station.

. соответствует любому символу, в то время как *? является ленивым квантификатором , потребляющим столько символов, сколько необходимо для соответствия шаблону.

Вот рабочий пример:

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

Попробуйте!

...