Get numbers after php regex string

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

rw200-208-ab66
fg200-cr30-201

      

I need to print ab66

and cr30

.

I tried using strpos

:

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

      

It doesn't work for the second item.

+3
php regex


source to share


2 answers


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
)

      

+2


source to share


You can use \K

to discard previously matched characters from being printed in the final. Below regex will give you the number that exists next to ab

 or cr

.

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

      



To get a number with alphabets use

preg_match_all('~(?:ab|cr)\d+~', $str, $match);

      

+3


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics