如何在PHP中使用REGEX获取特定的字符串值

时间:2018-03-21 03:59:22

标签: php regex

我有一个字符串内容。

$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"

2 个答案:

答案 0 :(得分:1)

您可以使用/(?<=then).*(?=radishes)/获取thenradishes之间的所有内容。

$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中的要求是匹配包括thenradishes在内的所有内容,因此您可以使用/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];

您可以在https://regexr.com/

中练习

我的演示见https://regexr.com/3mj4v