0

我正在寻找一个正则表达式来匹配包含类似内容的给定 URL,
"/unknownnumber/knownstring1-unknownstring.html"
以便使用 PHP 将其重定向到其他新 URL,例如
"/unknownnumber/knownstring2-unknownstring"
保持 Google 索引 URL 处于活动状态。

我已经使用了 next 语句,但是$do_match返回0了,所以我做错了什么......

有人可以帮我处理正则表达式吗?

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

4 回答 4

2

点 (.)、破折号 (-) 是具有特殊含义的元字符。

如果 'unknownnumber' 是字符串的数字部分,那么正则表达式模式将如下所示:

$do_match = preg_match('/\/(\d+)\/knownstring1\-([^\.]+)\.html/', $input, $matches);
于 2012-12-28T07:48:03.017 回答
2

A$是行尾标记。您需要将它放在正则表达式的末尾,并且还意味着.您需要转义它的文字。

preg_match('~"([0-9]+)/knownstring1-(.*?)\.html"$~'....
于 2012-12-28T07:48:39.847 回答
1
$myURL = "/unknownnumber/knownstring1-unknownstring.html";
if(preg_match('#"/(\d+)/knownstring1-(.*)\.html"#', $myURL, $matches))
    var_dump($matches);

输出:

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 > 
于 2012-12-28T08:00:17.053 回答
0

试试这个:

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

print_r 输出:

Array
(
    [0] => /123/knownstring1-unknownstring.html
    [1] => 123
    [2] => knownstring1
    [3] => unknownstring
)
于 2012-12-28T08:15:46.880 回答