我有一个字符串内容。
$string = "FIRST he ate some lettuces and some French beans, and then he ate some radishes AND then, feeling rather sick, he went to look for some parsley.";
这里我想采取一个特定的字符串
"then he ate some radishes"
如何使用REGEX进行操作?我只想在REGEX中
I want to pass just 2 parameters like
1. then
2. radishes
所以最后我想要输出"then he ate some radishes"
答案 0 :(得分:1)
您可以使用/(?<=then).*(?=radishes)/
获取then
和radishes
之间的所有内容。
$re = '/(?<=then).*(?=radishes)/';
$str = 'FIRST he ate some lettuces and some French beans, and then he ate some radishes AND then, feeling rather sick, he went to look for some parsley.';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
分解:
(?<=then)
:断言下面的正则表达式匹配
然后匹配字符然后字面上(区分大小写).*
匹配任何字符(行终止符除外)*
量词 - 在零和无限次之间匹配,尽可能多次,根据需要回馈(贪婪)(?=radishes)
:断言下面的正则表达式匹配
萝卜字面上匹配字符萝卜(区分大小写) OP中的要求是匹配包括then
和radishes
在内的所有内容,因此您可以使用/then.*radishes/
代替/(?<=then).*(?=radishes)/
要使正则表达式非贪婪,您应该选择/then.*?radishes/
和/(?<=then).*?(?=radishes)/
答案 1 :(得分:1)
只需使用此
即可$string = "FIRST he ate some lettuces and some French beans, and then he ate some radishes AND then, feeling rather sick, he went to look for some parsley.";
preg_match("/then(.*?)radishes/", $string, $matches);
echo $matches[0];
中练习