O
O
Outsider V.2016-02-01 21:40:48
Perl
Outsider V., 2016-02-01 21:40:48

How to make such a preg_match pattern?

You need to make a URL pattern that will match the following addresses:

/page_name.html
/page_name.html/1
/page_name.html/2
....
/page_name.html/999

At the same time, matches should contain the page_name value and the numbers after the slash. If there is no slash, then an empty string should get into the second variable.
Wrote this:
/^\/([\w\-]+)\.html[\/]?([\d]{1,3})?$/

But it also responds to such an address, for example:
/page_name.html14
How to make it match only if there is a slash and a number, and if only a number, then it does not match?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
O
Outsider V., 2016-02-01
@Audiophile

Thanks Stack Overflow
'/^\/([\w-]+)\.html(?|\/(\d{1,3})|())$/'

S
synapse_people, 2016-02-01
@synapse_people

<?php
$arr = array('/page_name.html',
'/page_name.html/1',
'/page_name.html/2',
'/page_name.html/999',
'/page_name.html14',
);

foreach($arr as $a) {

$matches = array();
preg_match('~\\/(?P<page_name>.*?)\.html(?:\\/(?P<num>\\d+))?$~', $a, $matches);
printf("%s => ",$a);

if ($matches) {
  printf(" %s; ", $matches['page_name']);

  if (isset($matches['num'])) {
    printf("[%d]", $matches['num']);
  } else {
    echo "No page set";
  }
} else {
  echo "No matches";
}

echo PHP_EOL;
}

Conclusion:
/page_name.html =>  page_name; No page set
/page_name.html/1 =>  page_name; [1]
/page_name.html/2 =>  page_name; [2]
/page_name.html/999 =>  page_name; [999]
/page_name.html14 => No matches

D
dimabdc, 2016-02-01
@dimabdc

/^\/(?P<name>\w+)\.html(\/?(?P<page>\d+))?$/igm
I recommend using https://regex101.com/ for compiling regular expressions

D
Dmitry, 2016-02-01
@mytmid

/^\/([\w\-]+)\.html(?:[\/]([\d]{1,3})?)?$/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question