Reputation: 9267
I want to write a regex with assertions to extract the number 55 from string unknownstring/55.1
, here is my regex
$str = 'unknownstring/55.1';
preg_match('/(?<=\/)\d+(?=\.1)$/', $str, $match);
so, basically I am trying to say give me the number that comes after slash, and is followed by a dot and number 1, and after that there are no characters. But it does not match the regex. I just tried to remove the $
sign from the end and it matched. But that condition is essential, as I need that to be the end of the string, because the unknownstring
part can contain similar text, e.g. unknow/545.1nstring/55.1
. Perhaps I can use preg_match_all, and take the last match, but I want understand why the first regex does not work, where is my mistake.
Thanks
Upvotes: 5
Views: 189
Reputation: 785651
Use anchor $
inside lookahead:
(?<=\/)\d+(?=\.1$)
You cannot use $
outside the positive lookahead because your number is NOT at the end of input and there is a \.1
following it.
Upvotes: 3