remove numbers from beginning of a line in a string with PHP
I hav开发者_如何学Ce a bunch of strings in php that all look like this:
10 NE HARRISBURG
4 E HASWELL
2 SE OAKLEY
6 SE REDBIRD
PROVO
6 W EADS
21 N HARRISON
What I am needing to do is remove the numbers and the letters from before the city names. The problem I am having is that it varies a lot from city to city. The data is almost never the same. Is it possible to remove this data and keep it in a separate string?
Check out regular expressions and preg_replace. $nameOfCity = preg_replace("/^\d+\s+\w{1,2}\s+/", "", $source);
Explained:
^
matches the beginning of the string\d+\s+
start with one or more numbers followed by one or more white-space characters\w{1,2}\s+
then there should be one or two letters followed by one or more white-space characters- The rest of the string should be the name of the city.
Cases not covered
- If there's only the text qualifier before the city name
- If there's only a number qualifier before the city name
- If there's only a number qualifier and a the cities name is two letters long.
If you want to be more precise, I assume you could enumerate all the possible letters before the city name (S|SE|E|NE|N|NW|W|SW)
instead of matching any one or two letter long strings.
See if the following works for you:
$new_str = preg_replace('/^([0-9]* \w+ )?(.*)$/', '$2', $str);
For each line, try this :
$arr = preg_split('/ /', $line);
if(count($arr) === 3)
{
// $arr[0] is the number
// $arr[1] is the letter
// $arr[2] is your city
}
else
{
// Like "PROVO" no number, no letter
}
Yes, this code is horible but it works... And it keeps all your data.
The important thing is to use preg_split
not the deprecated split
method.
If you want to get a list of cities as an array, try:
if(preg_match_all("/(\w+$)/", $source, $_matches)) {
$cities = $_matches[1];
}
精彩评论