我有以下我需要从循环中的字符串中删除。从字符串中删除
<comment>Some comment here</comment>
结果来自数据库,所以comment标签内的内容是不同的。
感谢您的帮助。
想通了。以下似乎是诀窍。
echo preg_replace('~\<comment>.*?\</comment>~', '', $blog->comment);
我有以下我需要从循环中的字符串中删除。从字符串中删除
<comment>Some comment here</comment>
结果来自数据库,所以comment标签内的内容是不同的。
感谢您的帮助。
想通了。以下似乎是诀窍。
echo preg_replace('~\<comment>.*?\</comment>~', '', $blog->comment);
这可能是矫枉过正,但您可以使用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"
如果这是仅去除<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>");
感谢您的回复。我想删除评论标签以及里面的文字。 – 2012-01-12 18:34:02
所以你要删除的''标签?这个字符串中是否有其他HTML标签? –
2012-01-12 17:07:15
你想删除标签内的文字吗? – 2012-01-12 17:17:06
对我来说看起来像XML,所以'DOM'&'getELementsByTagName'应该在开箱即可使用... – Wrikken 2012-01-12 17:17:28