Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove tag but keep string between tag in php

Tags:

string

php

tags

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

like image 872
Miss Phuong Avatar asked Jul 29 '26 05:07

Miss Phuong


2 Answers

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

like image 182
Omar Freewan Avatar answered Jul 30 '26 21:07

Omar Freewan


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

like image 25
Amr Avatar answered Jul 30 '26 23:07

Amr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!