0

I want to remove this multi line with 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 = random number

hakre
  • 193,403
  • 52
  • 435
  • 836
prabowo
  • 15
  • 4
  • You want to remove the entire div? – Smern May 13 '13 at 14:55
  • Use a method from above link to remove that node. – kittycat May 13 '13 at 14:57
  • Removed response, hoping OP can clarify this question. – brbcoding May 13 '13 at 15:00
  • actually the problem is like this, i want to parse a page using simplehtmldom, and on that page contain that script (show up few times randomly inside the text) so i want to remove it, and to make it simple i want to use str_replace, but the problem the id is random and its multi line, i dont know how to make it work.. – prabowo May 13 '13 at 15:13
  • if the ID is random you need to use `preg_replace()` – HamZa May 13 '13 at 15:14
  • preg_replace / str_replace fine for me as long that code is gone :) (sorry still newbie here) – prabowo May 13 '13 at 15:16
  • cryptic, can u help me give sample code for my problem sir, bit confuse with explanation on that page – prabowo May 13 '13 at 15:25
  • this site is bad for asking for getting code written for you especially when a question is not precise. you normally can improve this by providing a code-example as context. And also keep in mind that only you ask yourself how something is written in code does not qualify a programming question. – hakre May 13 '13 at 15:36

2 Answers2

3

Try this:

$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);
mpyw
  • 5,526
  • 4
  • 30
  • 36
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)

Taken from here

Example in action here

Community
  • 1
  • 1
brbcoding
  • 13,378
  • 2
  • 37
  • 51