删除标签但在php中的标签之间保留字符串 [英] remove tag but keep string between tag in php
问题描述
我有从其他网站获取内容的文件.它包括很多:
<脚本>[随机] 字符串 2....<脚本>[随机] 字符串 n<script type="text/javascript">必须保留脚本<script type=text/javascript'>必须保留脚本
我想删除 <script>
和 </script>
但使用 PHP 保留它们之间的内容[随机] 字符串 ...".>
注意:str_replace 可以删除它们,但可能会影响其他脚本<script type="text/javascript">必须保留</script>
和 <script type='text/javascript'>必须保留</script>
.它将丢失必须保留脚本的关闭标签</script>
感谢您的帮助
//求解:
$content = preg_replace('/(<脚本>[随机] 字符串 2....<脚本>[随机] 字符串 n";$content = str_replace(array("<script>", "</script>"), "", $content);
由于您想摆脱 并同时保留
<脚本>[随机] 字符串 2....<脚本>[随机] 字符串 n<script type='text/javascript'>必须保留脚本<script type='text/javascript'>必须保留脚本";$dom->loadHTML($content);$scripts = $dom->getElementsByTagName('script');foreach ($scripts as $script) {如果 (!$script->hasAttributes()) {回声 $script->nodeValue ."<br>";}}
这将输出:
[随机] 字符串 1
[随机] 字符串 2
[随机] 字符串 n
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
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
这篇关于删除标签但在php中的标签之间保留字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!