如何使用preg_match查找两个或三个特定单词的字符串模式

时间:2019-01-16 23:05:16

标签: php

$lines ="do you want to cut paper here?";
$pattern = "do you '/(.*) to (.*)/' paper here?";

$matches = array();
preg_match($pattern, $lines, $matches);

var_dump($matches);

我遇到一个错误,我认为我使用的语法不正确,我尝试了许多类似的代码,但不满足我的要求。有人可以建议如何获得匹配的单词吗?

在此示例中,应缺少$matches[1],而应削减$matches[2]

先谢谢您

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的要求,则可以使用正则表达式:

<?php
$lines ="do you want to cut paper here?"; 
$pattern = "/do you ([^\s]+) to ([^\s]+) paper here\?/";

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

?>

它将显示以下结果:

array(3) {
  [0]=> string(30) "do you want to cut paper here?"
  [1]=> string(4) "want"
  [2]=> string(3) "cut"
}