Search code examples
phphtmlstringspecial-charactersstrip-tags

How I can HTML Special Chars remove without image SRC in string?


I tried to remove the HTML code in the string without remove the picture code

$HTMLstring = "<div class="h3 clr"><span>hello world</span><img src="/root/image.jpg"></div>

$plainText = htmlspecialchars(trim(strip_tags($HTMLstring)));

$plainText // "hello world"

My Purpose: $plainText // "hello world <img src="/root/image.jpg">"

Okey but I lost image link. What should I do to prevent this part <img src="/root/image.jpg"> from being remove?


Solution

  • You can strip tags except those in 2nd parameter of strip_tags() :

    $HTMLstring = '<div class="h3 clr"><span>hello world</span><img src="/root/image.jpg"></div>';
    $AlwaysHTMLString = strip_tags($HTMLstring, '<img>');
    echo $AlwaysHTMLString;
    // hello world<img src="/root/image.jpg">
    

    Don't use htmlspecialchars() or your <img> will not be rendered.