35

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 should be

1 2 3 4

How can I use a PHP function to get the desired output?

0

5 Answers 5

37
$str = "1 $nbsp;     2     3   4";
$new_str = str_replace(" ", '', $str);
Sign up to request clarification or add additional context in comments.

Comments

7

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 (Community warning: "This function is DEPRECATED as of PHP 8.2.0. Relying on this function is highly discouraged" - from PHP manual). 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

1 Comment

Even in 2016 I'd hardly imagine a case when utf8_decode() would be needed. Why anyone would want to decode an industry standard UTF-8 into a crippled ISO-8859-1?
3

if your string actually has "  ",

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

Comments

1
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.

Comments

0

This did the job for me:

preg_replace('~\x{00a0}~siu',' ',$content);

1 Comment

The s and i pattern modifiers seem totally pointless to me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.