使用PHP我想识别字符串中的预定义句子,并输出位于'target`的单词。我认为这可能是使用正则表达式完成的,但我没有编写它的知识。
句子例子:
所需的输出示例(作为数组):
答案 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+
,这意味着"一个或多个类似字的字符"。