Trim   with PHP

2020-05-20 08:42发布

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?

7条回答
Anthone
2楼-- · 2020-05-20 09:03
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.

查看更多
闹够了就滚
3楼-- · 2020-05-20 09:07

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

查看更多
我想做一个坏孩纸
4楼-- · 2020-05-20 09:10
$str = "1 $nbsp;     2     3   4";
$new_str = str_replace(" ", '', $str);
查看更多
Luminary・发光体
5楼-- · 2020-05-20 09:10

if your string actually has "  ",

$str="1       2     3   4";
$s = str_replace("  ","",$str);
print $s;
查看更多
爷、活的狠高调
6楼-- · 2020-05-20 09:11

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

查看更多
Root(大扎)
7楼-- · 2020-05-20 09:11

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

查看更多
登录 后发表回答