4

My string is $text1 = 'A373R12345'
I want to find last none digital number occurrence of this string.
So I use this regular expression ^(.*)[^0-9]([^-]*)
Then I got this result:
1.A373
2.12345

But my expected result is:
1.A373R
(It has 'R')
2.12345

Another example is $text1 = 'A373R+12345'
Then I got this result:
1.A373R
2.12345

But my expected result is:
1.A373R+
(It has '+')
2.12345

I want contain the last none digital number!!
Please help !! thanks!!

Nick Hung
  • 43
  • 1
  • 6

1 Answers1

7
$text1 = 'A373R12345';
preg_match('/^(.*[^\d])(\d+)$/', $text1, $match);
echo $match[1]; // A373R
echo $match[2]; // 12345

$text1 = 'A373R+12345';
preg_match('/^(.*[^\d])(\d+)$/', $text1, $match);
echo $match[1]; // A373R+
echo $match[2]; // 12345

Explanation of regex broken down:

^ match from start of string
(.*[^\d]) match any amount of characters where the last character is not a digit 
(\d+)$ match any digit character until end of string

enter image description here

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
kittycat
  • 14,983
  • 9
  • 55
  • 80
  • It works fine for my situtaion!! thanks!! Could you explain the regular expression for me? I only know.*[^\d] mean you wan to find the last none digital number – Nick Hung Nov 29 '12 at 03:24
  • @crypticツ What tool do you have used? – Epoc Nov 25 '14 at 16:38