获取某个词之前和之后的单词?

时间:2015-04-02 01:23:31

标签: php regex

  

孩子们喜欢看动画片Tom Jerry,但不喜欢Dora the Explorer!

我想在""之后得到第一个和最后一个字。所以上面会输出:Tom和Jerry

我已经考虑过使用爆炸函数和作为分隔符,但是会将所有内容都放到和的左边和右边。

  $string="The children likes to watch the cartoon Tom and Jerry but not Dora the Explorer!";

  list($left,$right)=explode('and',$string);

  echo $left; //The children likes to watch the cartoon Tom
  echo $right; //Jerry but not Dora the Explorer!

我以为我找到了solution but it was written for C#

2 个答案:

答案 0 :(得分:1)

你可以这样表达 //传递你的字符串并在这个表达式中匹配

$string="The children likes to watch the cartoon Tom and Jerry but not Dora the Explorer!";//this is your string
$find="and";//word to match
preg_match("!(\S+)\s*$find\s*(\S+)!i", $string, $match);
echo $before = $match[1];
echo $after = $match[2];

答案 1 :(得分:0)

难道你不能将$ left和$ right分解为使用space作为分隔符的数组,或沿着这些行的东西

$arrayLeft = explode(' ', $left);
$arrayRight = explode(' ', $right);

然后为左边做一个count数组来得到最后一个单词

$countArray = count($arrayLeft);
$countArray--;//or whatever syntax to make it minus 1

然后你有

$arrayLeft[$countArray]// for Tom
$arrayRight[0]// for jerry