简体   繁体   中英

PHP (URL) matching regex issue

I'm looking for a regex to match a given url wich contains something like
"/unknownnumber/knownstring1-unknownstring.html"
in order to redirect it with PHP to other new url like
"/unknownnumber/knownstring2-unknownstring"
to keep google indexed urls active.

I have used next statement, but $do_match returns 0 , so I'm doing something wrong...
Could someone help me with my regular expression?

$myURL = "/unknownnumber/knownstring1-unknownstring.html";
$do_match = preg_match('~"([0-9]+)/knownstring1-(.*?)$.html"~', $myURL, $matches);

Dot (.), dash (-) are meta characters that have special meaning.

If 'unknownumber' is a numeric part of your string, then regexp pattern would looke like this:

$do_match = preg_match('/\/(\d+)\/knownstring1\-([^\.]+)\.html/', $input, $matches);

A $ is a end of line marker. You need to place it at the end of the regex and also to mean a literal . you need to escape it.

preg_match('~"([0-9]+)/knownstring1-(.*?)\.html"$~'....
$myURL = "/unknownnumber/knownstring1-unknownstring.html";
if(preg_match('#"/(\d+)/knownstring1-(.*)\.html"#', $myURL, $matches))
    var_dump($matches);

outputs:

php > $exp = '#"/(\d+)/knownstring1-(.*)\.html"#';
php > $str = '"/23421/knownstring1-unknownstring.html"';
php > if(preg_match($exp, $str, $matches)) var_dump($matches); else echo 'nope' .     PHP_EOL;
array(3) {
  [0]=>
  string(40) ""/23421/knownstring1-unknownstring.html""
  [1]=>
  string(5) "23421"
  [2]=>
  string(13) "unknownstring"
}
php > 

Give this a try:

$myURL = "/123/knownstring1-unknownstring.html";
$do_matches = preg_match('#\/(\d+)\/(.*)\-(.*)\.html#', $myURL, $matches);
print_r($matches);

print_r output:

Array
(
    [0] => /123/knownstring1-unknownstring.html
    [1] => 123
    [2] => knownstring1
    [3] => unknownstring
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM