Space in contents only


function space($str) {
$strOut = '';
for ($i = 0; $i < strlen($str); $i++) {
$strOut .= ( substr($str, $i, 1) == ' ') ? '&nbsp;' : substr($str, $i, 1);
return $strOut;

$myVar='1 2  3';
echo space($myVar);


The code1 above produces the result1 above(Please notice there are 2 spaces between 2 and 3).

if the value of $myVar is like the below

<div style="color:red">1 2  3</div>

The result of it will be '<div style=“color:red”>1 2  3</div>.

I like to remove   which is between open tag(<) and close tag(>).

I can remove with the code “str_replace(‘div&nbsp;’,'div ',$myVar);” in the case of the above, but there are variety of selectors and properties inside tags.

How can I remove all spaces   which is between open tag(<) and close tag(>) ?
I like to put   into contents (

1 2  3

) only which is outside tags instead of inside tags.

Well, you could do it in two steps…

  1. Replace all ’ ’ with  
  2. Replace all &nbsp between < and > with ’ ’

(Hint: [FPHP]preg_replace[/FPHP] and [FPHP]preg_replace_callback[/FPHP])

I can do Replace all ’ ’ with   using the code below.

$myVar=str_replace(' ','&nbsp;',$myVar);

Do you mean Replace all ’ ’   using preg_replace?
And Replace all &nbsp between < and > with ’ ’ using preg_replace_callback?

Which part of the page can Replace all   between < and > with ’ '?

You can do the first step with str_replace, yes.
You’ll need str_replace in the callback of preg_replace_callback for the second step.