2014-02-08 51 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);