PHP str_replace function problem

  • #1

Main Question or Discussion Point

I have this PHP code to edit all HTML text to be displayed so that it wont appear as HTML but as standard text.

<?php
function htmlformat($sinput){

$newphrase = str_replace("<", "&lt;", $sinput);
$newphrase = str_replace(">", "&gt;", $newphrase);
$newphrase = str_replace(chr(13),"<br>",$newphrase);
$newphrase = str_replace(chr(34), "&quot;", $newphrase);
$newphrase = str_replace(chr(32), "&nbsp;",$newphrase);


$newphrase=str_replace("","<font color=red>",$newphrase);

$newphrase=str_replace("
","</font>",$newphrase);

$newphrase=str_replace("","<img src=",$newphrase);

$newphrase=str_replace("",">",$newphrase);


return $newphrase;
}
?>


the problem is this part of the code

$newphrase = str_replace(chr(32), "&nbsp;",$newphrase);


it only replace the single spaces with &nbsp;
but what about multiple spaces?
when I have 2 more spaces on the text it cant seem to replace it with &nbsp;
 

Answers and Replies

  • #2
34,286
10,325
I can't reproduce that problem, works fine for me:
Code:
$newphrase = "a  b";
$newphrase = str_replace(chr(32), "&nbsp;",$newphrase);
              
echo $newphrase;
a&nbsp;&nbsp;b

If you use this as HTML code then a browser will convert these &nbsp; back to spaces and then display only one. If you want to avoid that, use "&amp;nbsp;".
 
  • #3
1,516
617
... just curious, are you aware of the strip_tags() function?
 
  • #4
413
152
Sometime in the last nine'n'half years he/she may have figured it out :wink:
 
  • #5
34,286
10,325
These threads get hundreds to thousands of views from search engines over the years. Replies are not just helping the original poster.
 
  • Like
Likes hmmm27

Related Threads on PHP str_replace function problem

  • Last Post
Replies
2
Views
7K
  • Last Post
Replies
12
Views
830
  • Last Post
Replies
5
Views
3K
Replies
2
Views
1K
  • Last Post
Replies
4
Views
626
  • Last Post
Replies
6
Views
3K
  • Last Post
Replies
4
Views
5K
  • Last Post
Replies
2
Views
3K
  • Last Post
Replies
8
Views
6K
  • Last Post
Replies
8
Views
4K
Top