使用str_replace删除多行

时间:2013-05-13 14:53:55

标签: php str-replace multiline

我想用str_replace

删除这个多行
<div><i>Hello</i><br/>
<!-- Begin: Hello.text -->
<script src="http://site.com/hello.php?id=12345" type="text/javascript">
</script>
<!-- End: Hello.text --></div>

12345 =随机数

2 个答案:

答案 0 :(得分:2)

试试这个:

$pattern = <<< EOD
@<div><i>Hello</i><br/>
<!-- Begin: Hello\.text -->
<script src="http://site\.com/hello\.php\?id=\d++" type="text/javascript">
</script>
<!-- End: Hello\.text --></div>
?@
EOD;

echo preg_replace($pattern,'',$text);

答案 1 :(得分:0)

<?php
$html = '<div><i>Hello</i><br/><!-- Begin: Hello.text --><script src="http://site.com/hello.php?id=12345" type="text/javascript"></script><!-- End: Hello.text --></div>';

$doc = new DOMDocument();

// load the HTML string we want to strip
$doc->loadHTML($html);

// get all the script tags
$script_tags = $doc->getElementsByTagName('script');

$length = $script_tags->length;

// for each tag, remove it from the DOM
for ($i = 0; $i < $length; $i++) {
  $script_tags->item($i)->parentNode->removeChild($script_tags->item($i));
}

// get the HTML string back
$no_script = $doc->saveHTML();


echo $no_script;

// this removes every script tag from your input ($html)

取自 here

行动中的示例 here