2012-01-12 246 views
0

我有以下我需要從循環中的字符串中刪除。從字符串中刪除

<comment>Some comment here</comment> 

結果來自數據庫,所以comment標籤內的內容是不同的。
感謝您的幫助。

想通了。以下似乎是訣竅。

echo preg_replace('~\<comment>.*?\</comment>~', '', $blog->comment);

+2

所以你要刪除的''標籤?這個字符串中是否有其他HTML標籤? – 2012-01-12 17:07:15

+0

你想刪除標籤內的文字嗎? – 2012-01-12 17:17:06

+0

對我來說看起來像XML,所以'DOM'&'getELementsByTagName'應該在開箱即可使用... – Wrikken 2012-01-12 17:17:28

回答

1

這可能是矯枉過正,但您可以使用DOMDocument將字符串解析爲HTML,然後刪除標記。

$str = 'Test 123 <comment>Some comment here</comment> abc 456'; 
$dom = new DOMDocument; 
// Wrap $str in a div, so we can easily extract the HTML from the DOMDocument 
@$dom->loadHTML("<div id='string'>$str</div>"); // It yells about <comment> not being valid 
$comments = $dom->getElementsByTagName('comment'); 
foreach($comments as $c){ 
    $c->parentNode->removeChild($c); 
} 
$domXPath = new DOMXPath($dom); 
// $dom->getElementById requires the HTML be valid, and it's not here 
// $dom->saveHTML() adds a DOCTYPE and HTML tag, which we don't need 
echo $domXPath->query('//div[@id="string"]')->item(0)->nodeValue; // "Test 123 abc 456" 

DEMO:http://codepad.org/wfzsmpAW

1

如果這是去除<comment />標籤的問題,一個簡單的preg_replace()str_replace()會做:

$input = "<comment>Some comment here</comment>"; 

// Probably the best method str_replace() 
echo str_replace(array("<comment>","</comment>"), "", $input); 
// some comment here 

// Or by regular expression...  
echo preg_replace("/<\/?comment>/", "", $input); 
// some comment here 

或者,如果裏面還有其他的標籤,你想除去少數幾個,使用strip_tags()及其可選的第二個參數來指定允許的標籤。

echo strip_tags($input, "<a><p><other_allowed_tag>"); 
+0

感謝您的回覆。我想刪除評論標籤以及裏面的文字。 – 2012-01-12 18:34:02