Remove specific HTML tags using PHP

0 min read 83 words

There are times when you want to remove a specific HTML tag from an HTML block of text.

This could be an anchor(<a/>) or an image(<img/>) perhaps.

You can use preg_replace to do this quite quickly and efficiently.

Remove an anchor:

$content = "Sample text <a href="#">Our anchor</a>. Etc etc";
$content = preg_replace('/<\/?a[^>]*>/','',$content);
//$content is now -> "Sample text. Etc etc";

Remove an image:

$content = "Sample text <img src="our_image.jpg">. Etc etc";
$content = preg_replace('/<\/?a[^>]*>/','',$content);
//$content is now -> "Sample text. Etc etc";
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags