eozzy
eozzy

Reputation: 68670

Regex to search in reverse

Haystack: 14201-33-0.html

Needle: 0

Regex: ((?:-[^-]*))$

Matches: -0.html

So I need to capture the digits from the last - until the ., excluding those chars themselves. I'm not good with regex so can't quite figure how to match 0 exactly. It can be 1 or 2 digits in place of 0.

Upvotes: 1

Views: 121

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You may use the following regex:

'~-(\d+)\.\D*$~'

See the regex demo

Details:

  • - - a hyphen
  • (\d+) - Group 1: one or more digits
  • \. - a dot
  • \D* - zero or more chars other than digits (this may be changed to [a-zA-Z]+ or specific list of extensions, e.g. (?:html?|php))
  • $ - end of string.

PHP demo:

$re = '~-(\d+)\.\D*$~';
$str = '14201-33-0.html';
if (preg_match($re, $str, $match)) {
 echo $match[1];
}

Upvotes: 2

Related Questions