2012-12-06 69 views
2

我有文件PHP保持標籤之間的內容:刪除標籤,但如果匹配的字符串

<?php 
$content = " 
<script> 
include string show_ads_1 and other string 1 
</script> 

<script> 
include string show_ads_2 and other string 2 
</script> 

<script> 
include string show_ads_x and other string x 
</script> 

<script> 
not include 'show _ ads _ x' --> keeping this 
</script> 

<script type=\"text/javascript\"> 
include string 'show_ads_x' but keeping this because <script type='text/javascript'> not <script> 
</script> 
"; 

//Only remove tag <script></script> if includes "show_ads" string 
$content = preg_replace('/(<script>)(show_ads.*?)(<\/script>)/s', '$2', $content); 
echo $content; 
?> 

如果<script>...</script>之間的內容包括字符串「show_ads_」它會刪除<script></script>但保留的所有內容。

但上面的腳本不起作用。沒有刪除。 我想在運行它,並查看源代碼,它看起來像:

include string show_ads_1 and other string 1 



include string show_ads_2 and other string 2 



include string show_ads_x and other string x 


<script> 
not include 'show _ ads _ x' --> keeping this 
</script> 

<script type="text/javascript"> 
include string 'show_ads_x' but keeping this because <script type='text/javascript'> not <script> 
</script> 
+1

怎麼辦這個「不行」?您的查看源示例顯示腳本標記已被刪除,正如您在您的要求中所述。 –

+0

@MarcB我認爲他試圖得到什麼;當您查看源代碼時,'

0

使用DOMDocument來執行,就像這樣:

<?php 

$dom = new DOMDocument(); 
$content = " 
    <script> 
    include string show_ads_1 and other string 1 
    </script> 

    <script> 
    include string show_ads_2 and other string 2 
    </script> 
    .... 
    <script> 
    include string show_ads_x and other string x 
    </script> 

    <script> 
    include string bla bla bla 
    </script> 

    <script> 
    not include 'show _ ads _ x' --> keeping this 
    </script> 

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

    <script type='text/javascript'> 
    include string 'show_ads_x' but keeping this because <script type='text/javascript'> not <script> 
    </script>  
"; 

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

foreach ($scripts as $script) { 
    if (!$script->hasAttributes()) { 
     if (strstr($script->nodeValue, "show_ads_")) { 
      echo $script->nodeValue . "<br>"; 
     } 
    } else { 
     echo "<script type='text/javascript'>$script->nodeValue</script>" . "<br>"; 
    } 
} 

?> 
+0

謝謝Amr,工作! –

+0

太好了,歡迎您的光臨! – Amr

相關問題