Answer the question
In order to leave comments, you need to log in
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
/^\/([\w\-]+)\.html[\/]?([\d]{1,3})?$/
Answer the question
In order to leave comments, you need to log in
<?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;
}
/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
/^\/(?P<name>\w+)\.html(\/?(?P<page>\d+))?$/igm
I recommend using https://regex101.com/
for compiling regular expressions
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question