2014-02-08 67 views
0

通常:PHP中可以爆炸幫助我分裂兩個因素?

$data = 'hello world&cool&stuff&here'; 

$explode = explode('&', $data); // returns array with hello world, cool, stuff, here 

現在這個數據

$data = 'hey this is a beautiful day #content_start#The World is Beautiful#content_end#'; 

我如何可以提取 「世界是美麗的」,從上面的字符串?

運行explode('#content_start', $data);然後explode('#content_end', $data);?或者有更簡單更合適的方式。

回答

1

你的想法會工作得很好。

只要做到這一點這樣的:

$data = 'hey this is a beautiful day #content_start#The World is Beautiful#content_end#'; 
$first = explode('#content_start#', $data); 
$second = explode('#content_end#', $first[1]); 
echo $second[0]; 

第一爆炸將返回字符串,其中,所述第一($first[0])將hey this is a beautiful day和第二($first[1])的陣列將是The World is Beautiful#content_end#。然後你可以使用第二個爆炸來獲得你想要的結果。


但是,更可讀的方法是使用RegEx來匹配您搜索的模式並逐字搜索您的字符串。代碼然後是:

$data = 'hey this is a beautiful day #content_start#The World is Beautiful#content_end#'; 
$matches = array(); 
preg_match('/#content_start#(.*)#content_end#/', $data, $matches); 
echo $matches[1]; 
0

爲什麼不使用這個?

$data = 'hey this is a beautiful day #content_start#The World is Beautiful#content_end#'; 
$parts = explode('#', $data); 
echo $parts[2]; 
0

使用explode不是最好的選擇。

你應該更好地利用strpossubstr

$start = '#content_start#'; 
$end = '#content_end#'; 
$startPos = strpos($data, $start) + strlen($start); 
$length = strpos($data, $end) - $startPos; 
$result = substr($data, $startPos, $length); 
0

這是正則表達式的工作:

$data = 'hey this is a beautiful day #content_start#The World is Beautiful#content_end#'; 
preg_match('/#content_start#(.*)#content_end#/s', $data, $matches); 
print_r($matches); 

這將顯示:

Array 
(
    [0] => #content_start#The World is Beautiful#content_end# 
    [1] => The World is Beautiful 
) 

所以$matches[0]包含原始匹配的字符串,和$matches[1]包含比賽。

1

試試這個....

$data = 'hey this is a beautiful day #content_start#The World is Beautiful#content_end#'; 
echo substr(strstr(implode(explode("end#",implode("{",explode("start#", implode(explode("#content_", $data)))))), '{'), 1);