您可以使用preg_match_all像這樣:
$matches = array();
preg_match_all('/(\/block\/[0-9]+\/page\/[0-9]+)/', '/block/2/page/2/block/3/page/4', $matches);
var_dump($matches[0]);
輸出:
array(2) {
[0]=>
string(15) "/block/2/page/2"
[1]=>
string(15) "/block/3/page/4"
}
Demo
編輯:This是我可以使preg_split做到最好。
$array = preg_split('#(/block/)#', '/block/2/page/2/block/3/page/4', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$result = array();
for($i = 0, $count = count($array); $i < $count; $i += 2)
{
$result[] = $array[$i] . $array[$i + 1];
}
如果您仍然需要循環以添加分隔符,那麼使用正則表達式不值得。只需使用自己的爆炸和預先設置分隔符:
$delimiter = '/block/'; $results = array();
foreach(explode($delimiter, '/block/2/page/2/block/3/page/4') as $entry)
{
if(!empty($entry))
{
$results[] = $delimiter . $entry;
}
}
Demo
最後編輯:解決了!下面是使用正則表達式的一個,preg_split
和PREG_SPLIT_DELIM_CAPTURE
$regex = '#(/block/(?:\w+/?)+(?=/block/))#';
$flags = PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY;
preg_split($regex, '/block/2/page/2/block/3/page/4', -1, $flags);
preg_split($regex, '/block/2/page/2/order/title/sort/asc/block/3/page/4', -1, $flags);
輸出解決方案:
array(2) {
[0]=>
string(15) "/block/2/page/2"
[1]=>
string(15) "/block/3/page/4"
}
array(2) {
[0]=>
string(36) "/block/2/page/2/order/title/sort/asc"
[1]=>
string(15) "/block/3/page/4"
}
Final Demo
你想這樣做在同一行或只是做呢? –
[有沒有辦法保持分隔符,而使用PHP爆炸或其他類似的功能?](http:// stackoverflow。問題/ 2938137/is-there-way-to-keep-delimiter-while-using-php-explode-or-other-similar-function) – Clive
我已經閱讀過這個問題,我不認爲它是重複的 – Purplefish32