Skip to content

Instantly share code, notes, and snippets.

@tedicela
Last active December 9, 2016 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tedicela/0b06265eefb8df41cb8256bb3f442916 to your computer and use it in GitHub Desktop.
Save tedicela/0b06265eefb8df41cb8256bb3f442916 to your computer and use it in GitHub Desktop.
Stripping certain xml/html tag from a string.
<?php
/*
//Usage:
$txt= '<h2>
<a
href="/w/index.php?title=Lorem_ipsum&amp;action=edit&amp;section=2"
title="Edit section: Discovery">edit< / a> <!-- This "a" will be stripped -->
<a href="/w/index.php?title=Lorem_ipsum&amp;action=edit&amp;section=2" title="Edit section: Discovery">edit< /a> <!-- This "a" will be stripped -->
<a href="/w/index.php?title=Lorem_ipsum&amp;action=edit&amp;section=2" title="Edit section: Discovery">edit</ a> <!-- This "a" will be stripped -->
<b>This will "a" be stripped</b>
<br><br><!-- These "br" will not be stripped-->
<span class="mw-editsection-bracket">]
</span></span>
</h2>';
$txt = strip_single_tag($txt, 'a');
$txt = strip_single_tag($txt, 'b');
echo $txt;
*/
function strip_single_tag($string, $tag){
$string = preg_replace('/<'.$tag.'(\s*|\s(.|\s)[^>]*)>/i', "", $string);
$string = preg_replace('/<\s*\/\s*'.$tag.'(\s*|\s(.|\s)[^>]*)>/i', "", $string);
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment