How to remove first empty space from string?

  • A+

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?


your suggested ltrim approach wouldn't delete the first empty space, it would delete all the space at the start of the string, for example: ltrim("foo bar") would return foo bar, not foobar (it would not delete the first empty space in the string)

use preg_replace with $limit, $str=preg_replace("//s/u","",$str,1); - this would remove the first space in $str , no matter where the first space is.

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


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: