Valentin Tanasescu
Valentin Tanasescu

Reputation: 106

Preg_match for alternative values in regex php

I want to match one of two posibilities in a regex.

$regex = "/^(& (sot-(<pagination>[0-9]+)) | (dorer-(<pagination>[0-9]+)) )? &?$/";
preg_match($regex, "&sot-6", $matches);

This regex should match for values like:

&sot-4
&dorer-56&
&sot-281&
&dorer-0

Which means "&"("sot-" or "dorer-")(number)(optional "&")

But (text)-(number) isn't the single format. That's why I need an extended regex format.

But it doesn't match at all. What should I do?

Upvotes: 1

Views: 259

Answers (1)

anubhava
anubhava

Reputation: 785611

You may use this shorter regex that works with all of your test cases:

^&[^-]+-(?<pagination>\d+)&?$

RegEx Demo

You may want to add more details in question if this is not matching your requirements.

RegEx Details:

  • ^&: Match & at line start
  • [^-]+; Match 1+ non-hyphen characters
  • -: Match a hyphen
  • (?<pagination>\d+): Match 1+ digits and capture it in group named pagination
  • &?$: Match optional & before end

Upvotes: 1

Related Questions