孩子们喜欢看卡通汤姆和杰瑞,但不喜欢看探险家多拉!
我想得到"answers"之后的第一个和最后一个单词,所以上面的输出为: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!
我以为我找到了一个解决方案,但它是为C#编写的。
您可以//传递字符串并在此表达式中匹配
$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];
难道你不能用空格作为delimeter或类似的东西将$left和$right分解成数组吗
$arrayLeft = explode(' ', $left);
$arrayRight = explode(' ', $right);
然后对左边做一个计数数组,得到最后一个单词
$countArray = count($arrayLeft);
$countArray--;//or whatever syntax to make it minus 1
那么你有
$arrayLeft[$countArray]// for Tom
$arrayRight[0]// for jerry