2015-04-02 84 views
0

孩子们喜欢看卡通汤姆杰瑞但不是探险家朵拉!获取某个单词之前和之后的单词吗?

我想后“和”所以上述具有的输出,以获得第一和最后一个字:汤姆和杰里

我一直在使用使用爆炸功能的考虑,并作为分隔符,但会得到一切都在左侧和右侧。

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

+3

您能发布您尝试过的代码吗? – mjuarez 2015-04-02 01:23:58

+0

PHP中的正则表达式与C#中的正则表达式相同。为什么这个答案不能帮助你? – Barmar 2015-04-02 01:28:59

回答

0

你不能只是爆炸留下的$ $,并直接进入使用空间分隔符,或类似的规定阵列

$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 
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]; 
相关问题