3

I need a regex that can actually get any number that is inserted after "ab" and "cr". For example, I have a string like this:

rw200-208-ab66
fg200-cr30-201

I need to print ab66 and cr30.

I have tried using strpos:

if (strpos($part,'ab') !== false) {
            $a = explode("ab", $part);
           echo 'ab'.$a[1];
    }

That does not work for the second item.

1
  • Have you tried something ? Commented May 20, 2015 at 13:02

2 Answers 2

3

You could use \K to discard the previously matched chars from printing at the final. The below regex would give you the number which exists next to ab or cr.

(?:ab|cr)\K\d+

To get the number with alphabets also, use

preg_match_all('~(?:ab|cr)\d+~', $str, $match);
Sign up to request clarification or add additional context in comments.

1 Comment

or (?:ab|cr)(\d+) use this regex and then get the number from group index 1.
2

Use this regex:

(?>ab|cr)\d+

See IDEONE demo:

$re = "#(?>ab|cr)\d+#"; 
$str = "rw200-208-ab66\nfg200-cr30-201"; 
preg_match_all($re, $str, $matches);
print_r($matches[0]);

Output:

Array
(
    [0] => ab66
    [1] => cr30
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.