Jump to content

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

Yeah, I don't need to trim it, and I got substr_count, but that doesn't remove the spaces, it just counts them.  I could use str_replace, but that would replace all instances of the substring.  I want all but one replaced.
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
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.