可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
$str = "1 $nbsp; 2 3 4";
$new_str = str_replace(" ", '', $str);
回答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
回答3:
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
回答4:
$str = " abc ";
echo trim($str, "\xC2\xA0"); //abc
回答5:
if your string actually has " ",
$str="1 2 3 4";
$s = str_replace(" ","",$str);
print $s;
回答6:
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
回答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.