[Solved] 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?

Solution #1:

$str = "1 $nbsp;     2     3   4";
$new_str = str_replace(" ", '', $str);
Respondent: Lotus Notes

Solution #2:

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

Respondent: Tobias Fünke

Solution #3:

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

$str = trim($str, " tnrx0BxC2xA0");

Same trim handling   html entities:

$str = trim(html_entity_decode($str), " tnrx0BxC2xA0");

This html_entity_decode and trim interaction is outlined in the PHP docs here:

Respondent: Chaoix

Solution #4:

$str = " abc ";

echo trim($str, "xC2xA0"); //abc
Respondent: Kenny

Solution #5:

A little late to answer but hopefully might help someone else. The most important while extracting content from html is to use utf8_decode() in php. Then all other string operations become a breeze. Even foreign characters can be replaced by directly copy pasting characters from browser into the php code. The following function replaces   with a space. Then all extra white spaces are replaced with a single white space using preg_replace(). Leading and trailing white spaces are removed in the end.

function clean($str)
    $str = utf8_decode($str);
    $str = str_replace(" ", " ", $str);
    $str = preg_replace('/s+/', ' ',$str);
    $str = trim($str);
    return $str;

$html = "1 $nbsp;     2     3   4";
$output = clean($html);
echo $output;

1 2 3 4

Respondent: Adam Ranganathan

Solution #6:

if your string actually has ”  “,

$str="1       2     3   4";
$s = str_replace("  ","",$str);
print $s;
Respondent: ghostdog74

Solution #7:

echo str_replace ( " ", "", "1       2     3   4" );

just remember you need to echo out the result of the str_replace and you alo dont need to worry about white spaces a the browser will only show one white space.

Respondent: Steve Obbayi

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.