2

I have file which get content from my other site. It is clude lot of:

<script>
[random] string 1
</script>

<script>
[random] string 2
</script>
....
<script>
[random] string n
</script>

<script type="text/javascript">
must keeping script
</script>

<script type=text/javascript'>
must keeping script
</script>

I want to REMOVE <script> and </script> but KEEP content between them "[random] string ..." using PHP.

Note: str_replace can remove them but may make hurst other scripts <script type="text/javascript">must keeping</script> and <script type='text/javascript'>must keeping</script>. It will lost close tag </script> of must keeping script

Thanks for helping

//SOLVED with:

$content = preg_replace('/(<script>)(.*?)(<\/script>)/s', '$2', $content);

Anyway, thanks for helping

Miss Phuong
  • 289
  • 1
  • 4
  • 15

5 Answers5

6
<?php
 $text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
 echo strip_tags($text);

 ?>

to get more info about strip tags see http://php.net/manual/en/function.strip-tags.php

Omar Freewan
  • 2,678
  • 4
  • 25
  • 49
3

Try this

$content = "
    <script>
    [random] string 1
    </script>

    <script>
    [random] string 2
    </script>
    ....
    <script>
    [random] string n
    </script>    
";

$content = str_replace(array("<script>", "</script>"), "", $content);

EDIT: Since you want to get rid of <script></script> and in the same time keep <script type="text/javascript"></script> and because using regexp to solve this kind of problems is a bad idea then try to use the DOMDocument like this:

$dom = new DOMDocument();

$content = "
    <script>
    [random] string 1
    </script>

    <script>
    [random] string 2
    </script>
    ....
    <script>
    [random] string n
    </script>

    <script type='text/javascript'>
    must keeping script
    </script>

    <script type='text/javascript'>
    must keeping script
    </script>    
";

$dom->loadHTML($content);
$scripts = $dom->getElementsByTagName('script');

foreach ($scripts as $script) {
    if (!$script->hasAttributes()) {
        echo $script->nodeValue . "<br>";
    }
}

This will output:

[random] string 1
[random] string 2
[random] string n

Community
  • 1
  • 1
Amr
  • 4,809
  • 6
  • 46
  • 60
0

If the content is of string type then you can use str-replace or str-ireplace

Damodaran
  • 10,882
  • 10
  • 60
  • 81
0

Then try strip_tags function http://php.net/manual/en/function.strip-tags.php?

senK
  • 2,782
  • 1
  • 27
  • 38
0

if the file is test.txt, use this code

<?php
$myFile = "test.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5000);
echo str_replace("</script>","",str_replace("<script>","",$theData));
fclose($fh);
 ?>
user7282
  • 5,106
  • 9
  • 41
  • 72