简体   繁体   中英

How do I remove the 7th and 8th to last characters in a string with PHP?

I want to remove the the 7th and 8th to last characters in a string.

$string = "Tucson AZ 85718"; 

I am trying to remove the state abbreviation. I have a bunch of these strings for different zip codes, so I can't just replace "AZ" with ''.

$string = substr($string, 0, -8) . substr($string, -5);

Demo:

php> $string = "Tucson AZ 85718";
php> echo substr($string, 0, -8) . substr($string, -5);
Tucson 85718

A regex would also do the job. This one would remove any 2-uppercase-character string and the space after it:

$string = preg_replace('/\b[A-Z]{2}\b /', '', $string);
$string = substr_replace($string, "", -8, 2);

not an php regexp expert, but it seems that

$string=preg_replace(" {w{1}} ", " ", $string);

would do the job for you. Should work with variable length city name.:wq

Disclaimer: I'm not American and don't know American postal addresses too well!

I would definitely do this with preg_replace or preg_match_all :

$string   = "Tucson AZ 85718"; 

// Don't be mislead by the second [A-Z], this means all uppercase characters
$pattern  = '/^(.+ )([A-Z]{2} )(\d+)$/';
preg_match_all($pattern, $string, $matches);

var_dump($matches);

This'll give you an array that looks like this:

array(4) {
  [0]=>
  array(1) {
    [0]=>
    string(15) "Tucson AZ 85718"
  }
  [1]=>
  array(1) {
    [0]=>
    string(7) "Tucson "
  }
  [2]=>
  array(1) {
    [0]=>
    string(3) "AZ "
  }
  [3]=>
  array(1) {
    [0]=>
    string(5) "85718"
  }
}

...where the 2nd, 3rd and 4th indexes will be the City, State code and Zip code respectively.

Alternatively, you could just strip the prefix with preg_replace :

$string   = "Tucson AZ 85718"; 
$pattern  = '/^(.+ )([A-Z]{2} )(\d+)$/';
$normalised = preg_replace($pattern, '$1$3', $string);

...which will give you "Tucson 85718", where the $1 and $3 in the second argument to preg_replace relate to the first and third blocks in parenthesis in the pattern ( (.* ) and (\\d{5}) respectively).

Assumptions:

  • States codes are all caps
  • Zip codes are all 5 digits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM