Ben Sinclair Ben Sinclair - 3 months ago 7x
PHP Question

Regex to match placeholders that contain HTML within them

I have placeholders that users can insert into a WYSIWYG editor (which contains HTML code). Sometimes when they paste from apps like Word etc it injects HTML within them.

Eg: It pastes

instead of

Here is an example of my regex code:

$html = '



<p>%<span class="blah">firstname</span>%</p>



<p>%<span class="blah"><span>firstname</span></span>%</p>

<div>other random <strong>HTML</strong> that needs to be preserved.</div>



echo '<pre>';
echo '</pre>';

Which outputs the following:

[0] => Array
[0] => %firstname%
[1] => %firstname%
[2] => %firstname%

[1] => Array
[0] => firstname
[1] => firstname
[2] => firstname


As soon as there is more than one span inside the placeholder it doesn't work. I'm not quite sure what to adjust in my regex.


How would I achieve this?


Try this Regex. It should help you out!