2015-04-02 132 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]; 
相關問題