簡體   English   中英

使用PHP從字符串中刪除具有類名稱的div

[英]remove a div with class name from a string with php

我需要從字符串中刪除特定的div。

我的代碼是:

$varz = "<div class="post-single">
<p> Hello all! </p>
<div class="ad">I want to remove this div</div>
</div>";

$varzfinal = preg_replace('/<div class="ad">.+<\/div>/siU', '', $varz); 
echo $varzfinal;

我需要刪除此: <div class="ad">I want to remove this div</div>

實現此目標的最佳方法是什么?

我們都很有耐心。 構建正則表達式以用於特定情況。 在這里,PHP社區為我們制作了DOMDocument 那么,為什么不使用最好的呢?

<?php
    $varz = <<< EOT
    <div class="post-single">
    <p> Hello all! </p>
    <div class="ad">I want to remove this div</div>
    </div>
EOT;

    $d = new DOMDocument();
    $d->loadHTML($varz);
    $s = new DOMXPath($d);
    foreach($s->query('//div[contains(attribute::class, "ad")]') as $t )
        $t->parentNode->removeChild($t);

    echo $d->saveHTML();

這是固定的PHP / regex,適用於“ ad”和“ ad1”類或任何其他數字:

<?php
$varz = '<div class="post-single">
<p> Hello all! </p>
<div class="ad">I want to remove this div</div>

<div class="ad2">I want to remove this div</div>
<div class="a">I dont want to remove this div</div>
<div> cool </div>
</div>';

$varzfinal = preg_replace('/<div class="ad(\d*)?">.+<\/div>/siU', '', $varz); 
echo $varzfinal;
?>

要修復編碼,請在本節中添加<meta charset="utf-8">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM