Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove   from a UTF-8 string?

My database is returning some strings like:

This is a string

This is a problem when the string is long enough and you have maximum width set:

<p style="width:50px">This&nbsp;is&nbsp;a&nbsp;string</p>

In order to get ride of &nbsp; entities I've tried to use the following filters without success:

$new = preg_replace("/&nbsp;/i", " ", $str);
$new = str_replace('&nbsp;', ' ', $str);
$new = html_entity_decode($str);

You have a PHP fiddle to see this in action (I've had to codify the string in hex from the database output; the string is in spanish, sorry).

How to deal with this? Why html_entity_decode() is not working? And what about the replace functions? Thanks.

like image 260
Ivan Avatar asked Feb 24 '15 19:02

Ivan


People also ask

How to completely uninstall a program?

To completely uninstall a program, you have two options. You can go through the manual process, or you can use some third-party software to do that for you. We will discuss both the techniques. Just follow steps to uninstall a software completely.

How do I use the Add/Remove Programs tool?

The Add/Remove programs tool lists all of the Windows-compatible programs that have an uninstall program or feature. You may need to manually remove the program from the Add/Remove Programs list if you uninstall a program and the registry key that is used to display the program name is not removed correctly:

How do I delete all downloads at once?

Go to the search bar next to the Windows Start menu. Enter File Explorer. Select File Explorer in the search results. Select the Downloads folder in the left pane. Type Ctrl + A to select all the files or choose them individually. Right-click the selected files and choose Delete.

How do I delete files from my computer?

Locate the file that you want to delete. Select the file and press your Delete key, or click Delete on the Home tab of the ribbon. Tip: You can also select more than one file to be deleted at the same time.


2 Answers

This gets tricky, its not as straight forward as replacing normal string.

Try this.

 str_replace("\xc2\xa0",' ',$str); 

or this, the above should work:

$nbsp = html_entity_decode("&nbsp;");
$s = html_entity_decode("[&nbsp;]");
$s = str_replace($nbsp, " ", $s);
echo $s;

@ref: https://moovwebconfluence.atlassian.net/wiki/pages/viewpage.action?pageId=1081435

like image 169
unixmiah Avatar answered Sep 22 '22 06:09

unixmiah


Get the html entities replace the one you want and decode back:

$str = str_replace('&nbsp;', ' ', htmlentities($new));
$new = html_entity_decode($str);
like image 39
miles_monroe Avatar answered Sep 22 '22 06:09

miles_monroe