Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does html_entity_decode replaces   also? If not how to replace it?

I have a situation where I am passing a string to a function. I want to convert   to " " (a blank space) before passing it to function. Does html_entity_decode does it?

If not how to do it?

I am aware of str_replace but is there any other way out?

like image 376
Abhishek Sanghvi Avatar asked Jun 08 '11 07:06

Abhishek Sanghvi


People also ask

What is html_entity_decode?

The html_entity_decode() is used to convert HTML entities to their application characters.

How do I decode HTML entities?

The html_entity_decode() function converts HTML entities to characters. The html_entity_decode() function is the opposite of htmlentities().

What's the difference between HTML entities () and htmlspecialchars ()?

Difference between htmlentities() and htmlspecialchars() function: The only difference between these function is that htmlspecialchars() function convert the special characters to HTML entities whereas htmlentities() function convert all applicable characters to HTML entities.

What is the use of Htmlspecialchars in PHP?

The htmlspecialchars() function converts some predefined characters to HTML entities.


2 Answers

Quote from html_entity_decode() manual:

You might wonder why trim(html_entity_decode(' ')); doesn't reduce the string to an empty string, that's because the ' ' entity is not ASCII code 32 (which is stripped by trim()) but ASCII code 160 (0xa0) in the default ISO 8859-1 characterset.

You can use str_replace() to replace the ascii character #160 to a space:

<?php
$a = html_entity_decode('>&nbsp;<');
echo 'before ' . $a . PHP_EOL;
$a = str_replace("\xA0", ' ', $a);
echo ' after ' . $a . PHP_EOL;
like image 199
Salman A Avatar answered Sep 18 '22 08:09

Salman A


html_entity_decode does convert &nbsp; to a space, just not a "simple" one (ASCII 32), but a non-breaking space (ASCII 160) (as this is the definition of &nbsp;).

If you need to convert to ASCII 32, you still need a str_replace(), or, depending on your situation, a preg_match("/s+", ' ', $string) to convert all kinds of whitespace to simple spaces.

like image 38
Aurimas Avatar answered Sep 18 '22 08:09

Aurimas