2015-04-29 53 views
0

我試圖將一段文本(實際上是html)分成兩部分,即頂部和底部。文本中的「標識符」(< - #SPLIT# - >)標記要拆分的位置。如何使用CR(LF)字符從標識符preg_replace到文本結尾

爲了得到上部我有以下的preg_replace,做工作:

$upper = preg_replace('/<--#SPLIT#-->(\s*.*)*/', '', $text); 

這給我留下了所有之前出現的文本「< - #SPLIT# - >」。

爲了得到下部我想出了下面的preg_replace不正常工作:

$lower = preg_replace('/(\s*.*)*<--#SPLIT#-->/', '', $text); 

這將返回一個空字符串。

如何解決第二個問題?

+0

你可以給一個樣品輸入你想要的輸出?這可能可以用一個正則表達式來完成。 – chris85

+0

在文本中只有一個「<--#SPLIT#-->」?並且'<--#SPLIT#-->'是一個文字字符串? –

+0

爲什麼preg_replace?爲什麼不preg_split? – bstakes

回答

1

這是更好地使用:

explode('<--#SPLIT#-->', $text); 

示例代碼:

$text = 'Foo bar<--#SPLIT#-->Baz fez'; 
$temp = explode('<--#SPLIT#-->', $text); 
$upper = $temp[0]; 
$lower = (count($temp > 1) ? $temp[1] : ''); 

// $upper == 'Foo bar' 
// $lower == 'Baz fez' 
+0

爲什麼我沒有想到這一點?謝謝。 –

相關問題