Replace All Spaces in HTML With   Except in HTML Tags Using PHP

  • Home /
  • Blog Posts /
  • Replace all spaces in HTML with   except in HTML tags using PHP

If you would like to replace all the spaces in an HTML string with   so that you can render it out to the browser but you also want to retain current spaces in HTML tags you can use the below method:

$inputString = '<span class="color:red">1</span> 2 3';
$outputString = preg_replace_callback("#>[^<]+<#","relSpaces",$inputString);

function relSpaces($match){return str_replace(" ","'",$match[0]);}

This will replace:
<span>1</span> 2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3

..to look like this:

<span>1</span> 2''''''' 3