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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With