iamjonesy
iamjonesy

Reputation: 25122

PHP Regex for this pattern

Need help with a regular expression.

1) Format:

 Advisor Geologist – HighMount Exploration & Production LLC – Oklahoma City, OK

I'd like to get the text between the last character and the dash. ie. Oklahoma City, OK. Note the text might contain multiple dashes.

Tried this:

~-([.*$]+)~

Trying to get between the dash and the end of the string (.*$). Need to know how to check for the last occurrence of the dash.

Upvotes: 0

Views: 96

Answers (4)

Ωmega
Ωmega

Reputation: 43673

If you need to use regex, then go with

$pattern = '/[^\s–-][^–-]*?(?=\s*$)/';
preg_match($pattern, $subject, $matches);

Test this demo here.

Upvotes: 1

nickb
nickb

Reputation: 59699

You don't need a regular expression, explode() the string on the dash, and take the last element.

$str = 'Advisor Geologist – HighMount Exploration & Production LLC – Oklahoma City, OK';
$arr = explode( '–', $str);
$last = trim( end( $arr));
echo $last;

Much more efficient.

Upvotes: 8

biakaveron
biakaveron

Reputation: 5483

Also strrpos() can help.

 $str = 'Advisor Geologist – HighMount Exploration & Production LLC – Oklahoma City, OK';
 $result = trim(substr($str, strrpos($str, '-')+1));

For fixed formats you can use list() & explode():

 $str = 'Advisor Geologist – HighMount Exploration & Production LLC – Oklahoma City, OK';
 list($occupation, $company, $city) = explode('-', $str);

Upvotes: 0

Botond Balázs
Botond Balázs

Reputation: 2500

If you need a regex, this is the simplest one I can think of:

'/\s*([^-]+)\s*$/'

Let's see how it works:

  • \s* matches zero or more whitespace characters (spaces, tabs, etc.)
  • ([^-]+) matches one or more characters that are not dashes
  • \s* matches zero or more whitespace characters (spaces, tabs, etc.)
  • $ matches the end of the string

Please note that what the character in your post is not a simple dash. It is some other Unicode character. If you need to match that too, you should update the regex this way:

'/\s*([^-–]+)\s*$/'

Here is a code sample:

preg_match(
    '/\s*([^-]+)\s*$/',
    'Advisor Geologist – HighMount Exploration & Production LLC - Oklahoma City, OK',
    $matches);
$city = $matches[1];

Upvotes: 0

Related Questions