2015-04-03 91 views
1

我需要獲取兩個分隔符之間的內容。我正在寫一個函數,以便我只能得到我想返回的部分。PHP在獲取內容的範圍內

HTML文件

<subject> 
    Subject line goes here 
</subject> 
<message> 
    Message text goes here 
</message> 

例如,函數可能是這樣的:

功能

public function get($section = '', $template = '') { 
    if(empty($section)) { 
     return false; 
    } 
    if(empty($template)){ 
     return false; 
    } 
    if(!file_exists($template)) { 
     return false; 
    } 

    $content = file_get_contents($template); 

    if($content) { 
     // Get chosen section 
    } 

} 

echo $this->get('message', 'myfile.html'); 

輸出

Message text goes here 
+0

請注意,由於標籤嵌套的方式,正則表達式通常是處理HTML文檔的糟糕選擇。查看鏈接的答案,瞭解更強大的替代方法。 – IMSoP 2015-04-03 14:56:21

回答

1

你不應該使用正則表達式來解析XHTML因爲y҉o̶u͢可以得到奇怪的內容,但如果你仍然想這樣做,你可以使用這樣的正則表達式:

<message>([\S\s]*?)</message> 

Working demo

PHP代碼:

$re = "@<message>([\\S\\s]*?)</message>@"; 
$str = "<subject>\n Subject line goes here\n</subject>\n<message>\n Message text goes here\n</message>"; 

preg_match_all($re, $str, $matches); 

順便說一句,我會使用一個html解析器來代替。