孩子们喜欢看动画片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!
答案 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