简体   繁体   English

如何在PHP中使用Regex从句子中提取主题/人?

[英]How to extract Subject/Person from sentence using Regex in PHP?

I want to match and extract subject and person from the following format of strings: 我想从以下格式的字符串中匹配并提取主题和人:
((When|Where) is)? (((何时|在哪里)是)? (my|the)? (我的)? (next)? (下一个)? (subject)? (学科)? (meeting|event)? (会议|事件)? (with (person))? (与(人)一起)?

Possible sentences: 可能的句子:

When is my meeting with David Sharma(Person=David Sharma)? 我什么时候与David Sharma(Person = David Sharma)见面?
Where is the lunch(Subject=Lunch) meeting? 午餐(主题=午餐)会议在哪里?
When is the Friday lunch(Subject=Friday Lunch)? 星期五的午餐时间(主题=星期五的午餐)?
Where is my next dinner(Subject) event with John(Person)? 我与约翰(人物)的下一个晚餐(主题)活动在哪里?

Here is my result after various attempts but some query or the other doesn't match properly: 这是经过各种尝试后的结果,但是某些查询或其他查询不正确:

 if (preg_match("/(?:(?:when|where)\s+is\s+)?(?:(?:my|the|your)\s+)?(?:next\s+)?((\S+\s+|\S+\s+\S+)+)?(?:(?:event|meeting)\s+)?(?:with\s+(.*))?/", $query, $matches)) {  
  print_r($matches[1]); //subject  
  print_r($matches[2]); //person  
}

Try Regex: ^(?:when|where) is(?: (?:my|the|your))?(?: next)?(?: (?:((?!event|meeting)[\\w ]+?)))?(?: (?:event|meeting))?(?: with ([\\w ]+))?\\?$ 试试Regex: ^(?:when|where) is(?: (?:my|the|your))?(?: next)?(?: (?:((?!event|meeting)[\\w ]+?)))?(?: (?:event|meeting))?(?: with ([\\w ]+))?\\?$

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM