noobie-php
noobie-php

Reputation: 7233

Regex for picking a Value After "-"

Hi I need a Regex that can actually get any letter that is inserted after "-" dash e.g i have a string that says

 "UpTown-R" , "Category-C"

What I get in return is "R" , "C".

Upvotes: 2

Views: 18312

Answers (6)

Alessandro Vendruscolo
Alessandro Vendruscolo

Reputation: 14877

A simple

-(.+)$

Will get everything that it's after the first dash; note that with this string foo-bar-baz you will match -bar-baz, and bar-baz will be in first group.

If you have to match only letters,

-([A-Za-z]+)$

Will suffice. Your result will be in the $1 group.

Alternatively, why don't you substr your string, starting from the last dash index way to end of the string?

Upvotes: 2

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76405

Why would you use slow regex's for this, why not just explode the string on '-'?

$str = 'UpTown-R';
$arr = explode('-',$str);
$letter = $arr[1];
$letterSage = $arr[1][0]; // to be sure you only get 1 character.

This works just as well! Before writing regex's all over the place, think of these wise words: "If your solution consists of more than 3 regular expressions, you're part of the problem"

Upvotes: 1

stema
stema

Reputation: 92986

If is always the last part of the string, you can do this

/[^-]+$/

see it here on Regexr

[^-] is a character class that matches everything that is not a dash

+ quantifier means one or more of the preceding element

$ anchor for the end of the string

Upvotes: 8

Toto
Toto

Reputation: 91385

How about:

preg_match('/-([a-z])\b/i', $string, $match);

unicode compatibility:

preg_match('/-(\pL)\b/u', $string, $match);

The letter you want is in $match[1].

Upvotes: 3

Bartosz Węgielewski
Bartosz Węgielewski

Reputation: 208

Here you are:

(?<=-)(.)

Results are in group 1.

Tested using:

Upvotes: 3

eyurdakul
eyurdakul

Reputation: 912

try this regex;

/^.*\-(.*)$/

this way you get everything after the dash

Upvotes: 1

Related Questions