Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove numbers from beginning of a line in a string with PHP

Tags:

php

split

I have 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?

like image 340
shinjuo Avatar asked Dec 28 '22 00:12

shinjuo


2 Answers

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

Explained:

  1. ^ matches the beginning of the string
  2. \d+\s+ start with one or more numbers followed by one or more white-space characters
  3. \w{1,2}\s+ then there should be one or two letters followed by one or more white-space characters
  4. 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.

like image 113
Aleksi Yrttiaho Avatar answered Feb 24 '23 14:02

Aleksi Yrttiaho


See if the following works for you:

$new_str = preg_replace('/^([0-9]* \w+ )?(.*)$/', '$2', $str);
like image 34
Tim Cooper Avatar answered Feb 24 '23 16:02

Tim Cooper