Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active September 4, 2015 06:04
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 westonruter/27307ea745701b6abf88 to your computer and use it in GitHub Desktop.
Save westonruter/27307ea745701b6abf88 to your computer and use it in GitHub Desktop.
<?php
$registered_shortcodes_non_empty = array(
'shout',
'empty',
'quiet',
'nesting',
'nested',
);
$registered_shortcodes_empty = array(
'empty',
);
$post_content = '<div><p>This is the <em>first</em> paragraph.</p><p>Behold, a [shout bar="1"]loud[/shout] shortcode. [nesting] inside [nested] more inside [/nested] [/nesting] And an [empty foo="1"] one [quiet]too[/quiet].</p></div>';
$tagified_shortcodes = $post_content;
$tagified_shortcodes = preg_replace( '#\[(' . join( '|', $registered_shortcodes_empty ) . ')(\s?.*?)\]#', '<span data-shortcode="\1"\2></span>', $tagified_shortcodes );
$tagified_shortcodes = preg_replace( '#\[(' . join( '|', $registered_shortcodes_non_empty ) . ')(\s?.*?)\]#', '<span data-shortcode="\1"\2>', $tagified_shortcodes );
$tagified_shortcodes = preg_replace( '#\[/(' . join( '|', $registered_shortcodes_non_empty ) . ')\]#', '</span>', $tagified_shortcodes );
$doc = new DOMDocument();
@$doc->loadHTML( $tagified_shortcodes );
echo $doc->saveHTML( $doc->getElementsByTagName( 'div' )->item( 0 ) ) . PHP_EOL;
<div>
<p>
This is the
<em>first</em>
paragraph.
</p>
<p>
Behold, a
<span bar="1" data-shortcode="shout">loud</span>
shortcode.
<span data-shortcode="nesting">
inside
<span data-shortcode="nested"> more inside </span>
</span>
And an
<span data-shortcode="empty" foo="1"></span>
one
<span data-shortcode="quiet">too</span>
.
</p>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment