如何使用PHP删除字符串中的第7个和第8个到最后一个字符?
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 ''.
我想删除字符串中的第7个和第8个到最后一个字符。 p>
$ string =“Tucson AZ 85718”;
code> pre>
我正在尝试删除州名缩写。 我有一堆这些字符串用于不同的邮政编码,所以我不能只用''代替“AZ”。 p>
div>
$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