Miss Phuong
Miss Phuong

Reputation: 289

remove tag but keep string between tag in php

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

Upvotes: 2

Views: 6141

Answers (5)

Amr
Amr

Reputation: 5159

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

Upvotes: 3

user7282
user7282

Reputation: 5196

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);
 ?>

Upvotes: 0

Omar Freewan
Omar Freewan

Reputation: 2678

<?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

Upvotes: 6

senK
senK

Reputation: 2802

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

Upvotes: 0

Damodaran
Damodaran

Reputation: 11047

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

Upvotes: 0

Related Questions