labu77 labu77 - 1 month ago 10
HTML Question

How to remove "a" tag in every "cite" tag using php?

A string contains some

cite
tags with text and links

<cite></cite>


Orignal:

<cite>Quote from <a href="/page.php" class="link">Testuser » 29.09.2016 15:08</a>:</cite>


Result:

<cite>Quote from Testuser » 29.09.2016 15:08:</cite>


What is the fastest way to remove the link and keep the text only if between cite tags?

Thank you

Answer

Parsing HTML and using DOM is best solution but because you want fastest way, you can use regex. I used preg_replace_callback() to finding cite tag and iterate selected tags. In callback function use strip_tags() to remove HTML tags in selected cite.

$newStr = preg_replace_callback("/<cite>.*<\/cite>/i", function($matches){
    return strip_tags($matches[0], "<cite>");
}, $str);

Check result in demo

Comments