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?
$str = "1 $nbsp; 2 3 4";
$new_str = str_replace(" ", '', $str);
if your string actually has " ",
$str="1 2 3 4";
$s = str_replace(" ","",$str);
print $s;
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.
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));
A more inclusive answer for those who want to just do a trim:
$str = trim($str, " \t
\0\x0B\xC2\xA0");
Same trim handling html entities:
$str = trim(html_entity_decode($str), " \t
\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
$str = " abc ";
echo trim($str, "\xC2\xA0"); //abc
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