2017-05-26 50 views
0

使用PHP我想识别字符串中的预定义句子,并输出位于'target'的单词。我认为这可能可以使用正则表达式,但我没有写它的知识。使用PHP(Regex?)识别并获取预定义语句的值

文例:

  1. 其中机场目标在什么位置?
  2. 有多少个机场在目标
  3. 目标目标需要多长时间?

希望的输出的例子(作为数组):

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

回答

0

是的,请使用正则表达式,通过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+,这意味着“一个或多个字样字符”。