2

I want to replace multiple spaces for a single space in a string. please advise on how to do it. Example code:

  <?php
    $input="bikash&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ranjan&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nayak";
    echo $output =preg_replace('/(( )+|(\\n)+)/', '$2$3',$input);

    ?>

the output is coming :
"bikash     ranjan          nayak"

1
  • Don't you mean you want to replace multiple spaces with a single space? Commented Jul 5, 2013 at 11:36

7 Answers 7

4

You could use a regular expression

$output = preg_replace('!\s+!', ' ', $input);
Sign up to request clarification or add additional context in comments.

11 Comments

it`s not working rajeev you can check, i also trying lot of things using preg_replace() fuction
it won't work in OP's $input content
reason behind &nbsp;&nbsp;
can give for example rajeev
Replicating answers on duplicate questions surely is a fun way to harvest rep, isn't it? If it's a duplicate, flag it as one...
|
2

Try this one. It will display as a single space on browser

$output = str_replace("&nbsp", " ",$input);

1 Comment

ok thanks lastly resolved my replace a string . before that i was missing some thing but same thing i used not worked. thanks again
1

Try this

$output = implode("&nbsp;",array_filter(explode("&nbsp;",$input)));

2 Comments

not working : my code according to <?php $input="bikash&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ranjan&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nayak"; $output = implode("&nbsp;",explode("&nbsp;",$input)); echo $output = preg_replace('!\s+!', ' ', $output); ?>
@BikashNayak: try this $output = implode("&nbsp;",array_filter(explode("&nbsp;",$input)));
1
$output = preg_replace('!\(&nbsp;)+!', '&nbsp;', $input);

Comments

1

try this

$output = preg_replace('/\s+/', ' ',$input);

Comments

1

Added the extra line ($input = html_ent.....) which decodes the html entitiy's.

$input="bikash&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ranjan&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nayak";

$input = html_entity_decode($input);

echo $output =preg_replace('/(( )+|(\\n)+)/', '$2$3',$input);

Comments

1

Try this code

$input="bikash&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ranjan&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nayak";
$array = explode('&nbsp;', $input);
$output = implode('&nbsp;', array_filter($array));
echo $output;

One liner:

$output = implode('&nbsp;', array_filter(explode('&nbsp;', $input)));

2 Comments

you r right but code is too long "work good"
I can write it as one line if you want. The solution you selected is not correct. It will still put down multiple spaces, but the browser will show only 1 or 2. And the spaces are not "non breaking spaces".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.