Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the very first empty space at the start of a string?

Tags:

php

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?

like image 518
rob.m Avatar asked Jul 15 '18 14:07

rob.m


People also ask

How do I remove a space at the beginning of a string?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.

How do you remove the first space from a string in Java?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

What is the best way to remove whitespace characters from the start or end?

To remove whitespace characters from the beginning or from the end of a string only, you use the trimStart() or trimEnd() method.

Which function is used to remove whitespace from the start of string?

The trim() function removes whitespace and other predefined characters from both sides of a string.


1 Answers

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
like image 143
Pedro Lobito Avatar answered Oct 29 '22 09:10

Pedro Lobito