5

I have a string like:

" United States" and I'd like it to be "United States"

I use the following to replace the string for other reasons but I cannot figure out how to tell it to only remove the first empty space:

$title = usp_get_meta(false, 'usp-custom-8');
update_post_meta( $post->ID, 'usp-custom-8', str_replace('n Argentinan', 'Argentina', $title ));

I know I could use something like $str = ltrim($str); but I am not sure how to put it there and I don't want to risk to run the loop and create a disaster as it will go through my whole db.

In theory I could also run it in another bit of code that I have:

        $stateList = usp_get_meta(false, 'usp-custom-8');
        $stateList = ltrim($stateList);
        $stateList = explode(',', $stateList);
        foreach($stateList as $state) {
          array_push($countries, $state);
        }

But I get Array as a value. when using ltrim there.

So either I make it run a loop as the first example or that last piece of code, yet how can I remove the first empty space from the string?

rob.m
  • 9,843
  • 19
  • 73
  • 162
  • @IncredibleHat will it not trim replace the space in between ` United States` too? – rob.m Jul 15 '18 at 14:34
  • @IncredibleHat this didn't work `$stateList = trim(usp_get_meta(false, 'usp-custom-8'));` – rob.m Jul 15 '18 at 14:38
  • 2
    If $stateList is an array - `$stateList = array_map("trim", $stateList);` – Nigel Ren Jul 15 '18 at 14:39
  • Possible duplicate of [How to remove first whitespace of string](https://stackoverflow.com/questions/13066759/how-to-remove-first-whitespace-of-string) – James Jul 15 '18 at 15:12
  • @James not at all, I have read that answer, matter of fact I use ltrim – rob.m Jul 15 '18 at 15:25
  • 1
    It isn't very clear what you want. Generally when asked (as per your title) "remove first empty space" then `ltrim` would be the answer. In fact you state that you could use this but not sure how, hence the answers with `ltrim`. Your example is also misleading showing one whitespace at the start and then gone in your desired outcome. The only way your question became clear is from the accepted answer, but even the answerer was shocked. Your question would have been good to have something like "the single and first space that occurs in a string regardless of where it occurs in the string" :) – James Jul 15 '18 at 16:38
  • @James sorry but i did say "the first white space" and provided an example where there are two " United States" and provided the desidered outcome. Also provided the use of ltrim() and says I tried and what it gave me back. I'll change the title into "The very first empty space at the start of a string" – rob.m Jul 15 '18 at 16:56
  • 1
    "the very first empty space at the **start** of the string" - this is still a job for `ltrim` – James Jul 15 '18 at 23:02
  • @James hey man, look, it might be a job for ltrim() and I have wrongly used it as the question and the code provided says. Matter of fact, the whole question for both cases uses ltrim(). Thanks for your help and comments. The solution provided in the accepted answer works. – rob.m Jul 16 '18 at 05:06
  • This question is Unclear because there is a decidedly poor [mcve]. The sample input provided does an inadequate job of representing the necessary logic. This page should be closed. – mickmackusa Dec 04 '20 at 06:34

6 Answers6

5

I'm not entirely sure of what you're trying to do, but in theory you can use array_map() with the ltrim() function, or even trim(), as argument after exploding $stateList, i.e. (untested):

$stateList = array_map("ltrim",  explode(',', $stateList));
# loop...

  1. explode() - Split a string by a string arrays
  2. array_map() - Applies the callback to the elements of the given arrays
  3. ltrim() - Strip whitespace (or other characters) from the beginning of a string
  4. trim() - Strip whitespace (or other characters) from the beginning and end of a string
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
4

Use array_map function http://php.net/manual/en/function.array-map.php

function removeLeftEmptySpace($str) {
    return ltrim($str);
}

$arr = [' United states', 'Boston'];
print_r(array_map('removeLeftSpace',$arr));
Andrei Todorut
  • 4,260
  • 2
  • 17
  • 28
  • 2
    if it's to make the code more readable, okay, but `print_r(array_map('ltrim',$arr));` would work as well ^^ (although this approach wouldn't, strictly speaking, remove the first empty space from the string, unless the first empty space happened to be at the very start of the string) – hanshenrik Jul 15 '18 at 14:53
4

The suggested ltrim approach will not delete the first empty space. Instead it would delete all the spaces at the start of the string, i.e. ltrim("foo bar") would return foo bar, not foobar (it would not delete the first empty space in the string)

Instead use preg_replace with $limit, $str=preg_replace("/\s/u","",$str,1); - Which would remove the first space in $str, regardless of where the first space is.

update_post_meta( $post->ID, 'usp-custom-8', preg_replace("/\s/u","",$title,1));

https://www.reddit.com/r/MaliciousCompliance/

Anmol
  • 43
  • 6
hanshenrik
  • 19,904
  • 4
  • 43
  • 89
  • bingo! Thanks a lot. tried all other solution but this is the one. `$stateList = usp_get_meta(false, 'usp-custom-8'); $stateList = preg_replace("/\s/u","",$stateList,1); $stateList = explode(',', $stateList);` will accept it – rob.m Jul 15 '18 at 14:48
  • 2
    You have to be kidding me. Ok, question was entirely misleading that you actually literrally meant removing the 'first space' ... regardless if the first space is before the string, or in the middle of the string. Grats to @hanshenrik for spotting that. – IncredibleHat Jul 15 '18 at 14:54
  • @IncredibleHat why misleading? I have provided the real case example when I said " United States" ... – rob.m Jul 15 '18 at 15:00
  • 4
    @IncredibleHat I answered the question posed not the one I thought was intended as a joke, nobody is more surprised than me that it was what was wanted :p – hanshenrik Jul 15 '18 at 15:14
  • @rob.m Your example shows a single whitespace at the start of the string and your desired outcome that space has gone. This is why everyone suggested `ltrim()`. Glad you got your answer though – James Jul 15 '18 at 16:40
  • @James my own code within the question showed `ltrim()` before anyone has suggested – rob.m Jul 15 '18 at 16:53
  • @IncredibleHat "*regardless if the first space is before the string, or in the middle of the string*" still not sure, I think it's just the single first space in the string at the start /shrugs – James Jul 16 '18 at 09:41
3

You could loop and trim and put this all in a new array, like so:

$countries  = [' United States', 'Argentina', ' France'];
$countriesClean = array();

    foreach($countries as $country) {
      $cleanCountry = ltrim($country);
      array_push($countriesClean, $cleanCountry);
    }

In this case, Argentina is the only country name that does not require a cleanup. Demo

Dirk J. Faber
  • 4,360
  • 5
  • 20
  • 58
  • ehmm ok but this changes the whole code, I am running a loop in my second example, and each loop has only 1 country, so I don't have an array of countries... – rob.m Jul 15 '18 at 14:39
  • 1
    Ah I misunderstood. Luckily somebody was able to give you the correct answer. – Dirk J. Faber Jul 15 '18 at 14:51
2

Or you can just use preg_replace:

$stateList = "     United States  ,   Argentina   ,  France      ";

$stateList = preg_replace("#\s*,\s*#", ',', trim($stateList) );

print_r(explode(",", $stateList));

output is:

Array
(
    [0] => United States
    [1] => Argentina
    [2] => France
)
MrSmile
  • 1,217
  • 2
  • 12
  • 20
  • just tried `$stateList = usp_get_meta(false, 'usp-custom-8'); $stateList = preg_replace("#\s*,\s*#", ',', $stateList); $stateList = explode(',', $stateList); var_dump($stateList);` and I get `" india"`tried to also out preg after the explode and yet... – rob.m Jul 15 '18 at 14:46
  • @rob.m, yes I missed first space; `$stateList = preg_replace("#\s*,\s*#", ',', trim($stateList) ); ` It will work perfectly – MrSmile Jul 15 '18 at 14:48
1

If $title is string and you only want to remove white space at the beginning of string, you can try....

Code

$title = " United States";
if(strpos($title," ") === 0 ){
  $title = substr($title, -(strlen($title)-1));
}
var_dump($title);

I'm using === strict check, sometime strpos return false.

Output

string(13) "United States"

Demo

Shahnawaz Kadari
  • 1,423
  • 1
  • 12
  • 20