2012-01-12 23 views
0

ループ内の文字列から削除する必要がある以下のものがあります。文字列から削除

<comment>Some comment here</comment> 

結果はデー​​タベースからのもので、コメントタグ内の内容が異なります。
ありがとうございました。

それを実演しました。以下はそのトリックを行うようだ。

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

+2

だから、 '' タグを削除したいですか?この文字列に他のHTMLタグはありますか? –

+0

タグ内のテキストも削除しますか? –

+0

XMLに似ているようですので、 'DOM'と' getELementsByTagName'はかなりうまくいくはずです... – Wrikken

答えて

1

これはやりすぎかもしれないが、あなたは、タグを削除、HTMLなどの文字列を解析するDOMDocumentを使用することができます。

$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

これは、単純なpreg_replace()またはstr_replace()を行います<comment />タグを除去するだけの問題である場合:

$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()にオプションの第2パラメータを使用して、許容タグを指定します。

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

返事をありがとう。コメントタグとその内部のテキストを削除したいと思います。 –

関連する問題