使用PHP(正则表达式?)从预定义的句子中识别和获取价值

时间:2017-05-26 13:24:00

标签: php regex

使用PHP我想识别字符串中的预定义句子,并输出位于'target`的单词。我认为这可能是使用正则表达式完成的,但我没有编写它的知识。

句子例子:

  1. 机场目标位于何处?
  2. 目标中有多少个机场?
  3. 目标目标之间的航班有多长时间?
  4. 所需的输出示例(作为数组):

    1. 0 =>希思罗机场
    2. 0 =>法国
    3. 0 =>巴塞罗那,1 =>巴黎

1 个答案:

答案 0 :(得分:1)

是的,通过preg_match

使用正则表达式
$input = 'where is the airport heathrow located?';

$templates = [
    '/where is the airport (.*) located\?/i',
    '/how many airports are there in (.*)\?/i',
    '/how long does a flight between (.*) and (.*) take?/i',
];

foreach ($templates as $template) {
    if (preg_match($template, $input, $matches)) {
        var_dump($matches[1]);
    }
}

输出:

string(8) "heathrow"

在模板中,使用括号括起"变量"在你的"模板"。这定义了一个捕获子组,PHP将作为preg_match例程的一部分而被淘汰。在括号内,我使用.*表示匹配所有内容。这可能太宽容了。您可以尝试,例如\w+,这意味着"一个或多个类似字的字符"。