匹配两个单词之间的所有内容,而匹配的最后一个单词是可选的

时间:2015-11-12 01:46:58

标签: php regex preg-match

我需要捕捉'一'和'四'之间的所有内容,'四'是可选的。我们不知道“一”和“四”之间的区别。我尝试匹配它,但没有得到正确的结果。我做错了什么?

$text = "one two three four five six seven eight nine ten";
preg_match("~one( .+)(four)?~i", $text, $match);

print_r($match);

结果:

Array ( [0] => one two three four five six seven eight nine ten [1] => two three four five six seven eight nine ten )

需要结果:

Array ( [0] => one two three four five six seven eight nine ten [1] => two three [3] => four)

PS:是的,'四'必须是可选的。

2 个答案:

答案 0 :(得分:1)

在这里你需要使用交替运算符。

Installing com.example.app
DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/com.example.app"
    pkg: /data/local/tmp/com.example.app
Failure [INSTALL_FAILED_CONFLICTING_PROVIDER]


DEVICE SHELL COMMAND: pm uninstall com.example.app
DELETE_FAILED_INTERNAL_ERROR

DEMO

答案 1 :(得分:0)

默认情况下,重复操作符(例如"?"," *"," +"或{n,m})贪婪 - 他们会尝试匹配尽可能多的符号。您可以在此处阅读更多内容:What do lazy and greedy mean in the context of regular expressions?

为了让他们不贪心添加"?"在他们之后。像这样: "〜一个(。+?)(四个)?〜我"