Jump to content

removing all but one space from a string


jumpenjuhosaphat

Recommended Posts

Okay, I've seen this done before, but I can't seem to find it in the search engines again.

I need to check to see if there is more than one space in a users input, and if there is, I need to remove the extra spaces, leaving only the one.  Can someone tell me how to do this please?
Link to comment
https://forums.phpfreaks.com/topic/35015-removing-all-but-one-space-from-a-string/
Share on other sites

You can explode the string on a space, use the [url=http://www.php.net/array_filter]array_filter()[/url] function to remove all spaces from the result of the explode and use implode to put it back together again:
[code]<?php
function not_space($v) {
if ($v != ' ') return($v);
}
$str = 'This string    has    multiple  spaces    in it.';
$str2 = implode(' ',array_filter(explode(' ',$str),'not_space'));
echo '<pre>$str:' . $str . '<br>$str2:' . $str2 . '</pre>';
?>[/code]

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.