简体   繁体   English

PHP Regex将句子中的单词与其他某些特定单词匹配(可选)

[英]PHP Regex to match word in a sentence with optionally only other certain words

I'm looking for a PHP regex to match a word in a sentence that will also optionally permit some other words in the sentence but the match should fail if there are any other words in the sentence that are not in the allowed list. 我正在寻找一个PHP正则表达式来匹配句子中的单词,该单词也可以选择允许句子中的其他单词,但是如果句子中有其他单词不在允许列表中,则匹配失败。 For eg: 例如:

The quick fox

Here I'm looking for fox. 在这里我正在寻找狐狸。 'The' and 'quick' are ok too if they appear. 如果出现“ the”和“ quick”,也可以。 Since those words are optional then just 由于这些词是可选的,因此

fox 

would be ok too. 也可以。 However, 然而,

The quick brown fox

is not ok. 不好。 I don't want a brown fox. 我不要棕狐狸。

Feel free to suggest another way of doing this too but it needs to be blazing fast. 也可以随意提出另一种方法,但这需要快速发展。

EDIT: The words will come before fox but they can appear in any order so 编辑:单词将出现在fox之前,但它们可以以任何顺序出现,因此

 quick The fox

should match too. 也应该匹配。

只需将前两个字设为可选即可。

^(?:(?:The )?(?:quick )?fox|(?:quick )(?:The )?fox|(?:fox )?(The )?quick|(?:The )?(?:fox )?quick)$

Ok I think I found a solution that's not too complicated and so far as I've tested, it seems to work with the results I want 好的,我认为我找到了一个不太复杂的解决方案,据我测试,它似乎可以满足我想要的结果

 ^(?(?=\b)(?:The|quick|\W)|.)+?fox

I'm checking here at each character to see if it's a word boundary. 我在这里检查每个字符,看是否是单词边界。 If it is then you must match 'the' or 'quick' or a non-word character at that point (indicating you're at the end of the word). 如果是,则必须在该点上匹配“ the”或“ quick”或一个非单词字符(表明您在单词的末尾)。 This will go on until I match 'fox'. 直到我匹配“ fox”为止。 If I match any other words than the ones allowed the match fails. 如果我匹配允许的单词以外的其他单词,则匹配失败。

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

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