Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim   with PHP

I have a sentence like this.

1       2     3   4

As you see, in between 1 2 and 3 text, there are extra spaces. I want the output with only one space between them. so my output will be 1 2 3 4.

If I use trim, it can only remove white space, but not that   How can I use PHP trim function to get the output like this?

like image 539
spotlightsnap Avatar asked Mar 26 '10 03:03

spotlightsnap


2 Answers

Found this at php.net, works great:

$myHTML = " abc";  $converted = strtr($myHTML, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));  trim($converted, chr(0xC2).chr(0xA0)); 

Source: http://php.net/manual/en/function.trim.php#98812

like image 90
Tobias Fünke Avatar answered Sep 27 '22 19:09

Tobias Fünke


A more inclusive answer for those who want to just do a trim:

$str = trim($str, " \t\n\r\0\x0B\xC2\xA0");

Same trim handling   html entities:

$str = trim(html_entity_decode($str), " \t\n\r\0\x0B\xC2\xA0");

This html_entity_decode and trim interaction is outlined in the PHP docs here: http://php.net/manual/en/function.html-entity-decode.php#refsect1-function.html-entity-decode-notes

like image 36
Chaoix Avatar answered Sep 27 '22 18:09

Chaoix