Remove numbers from beginning of line in line using PHP

I have a bunch of lines in php that look like this:

10 NE HARRISBURG
4 E HASWELL
2 SE OAKLEY
6 SE REDBIRD
PROVO
6 W EADS
21 N HARRISON

What I need to do is delete the numbers and letters on behalf of the city. The problem I am facing is that it varies greatly from city to city. The data practically do not match. Is it possible to delete this data and save it on a separate line?

+3
source share
4 answers

See if the following works for you:

$new_str = preg_replace('/^([0-9]* \w+ )?(.*)$/', '$2', $str);
+1
source

Check out regular expressions and preg_replace .$nameOfCity = preg_replace("/^\d+\s+\w{1,2}\s+/", "", $source);

Explanations:

  • ^ matches the beginning of a line
  • \d+\s+ start with one or more numbers followed by one or more space characters
  • \w{1,2}\s+, ,
  • .

,

  • , .

, , (S|SE|E|NE|N|NW|W|SW) , .

+6

For each line, try the following:

$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 terrible, but it works ... And it stores all your data. It is important to use a preg_splitnon-obsolete method split.

+1
source

If you want to get the list of cities as an array, try:

if(preg_match_all("/(\w+$)/", $source, $_matches)) {
  $cities = $_matches[1];
}
+1
source

Source: https://habr.com/ru/post/1795371/


All Articles