我正在寻找一个正则表达式来匹配给定的内容,其中包含类似的内容
"/unknownnumber/knownstring1-unknownstring.html"
为了将它与PHP重定向到其他新的URL,如
"/unknownnumber/knownstring2-unknownstring"
以保持Google索引网址有效。
我使用了下一个语句,但是$do_match
返回0
,所以我做错了什么......
有人可以用我的正则表达式帮助我吗?
$myURL = "/unknownnumber/knownstring1-unknownstring.html";
$do_match = preg_match('~"([0-9]+)/knownstring1-(.*?)$.html"~', $myURL, $matches);
答案 0 :(得分:2)
点(。),短划线( - )是具有特殊含义的元字符。
如果'unknownumber'是你的字符串的数字部分,那么regexp模式将会像这样:
$do_match = preg_match('/\/(\d+)\/knownstring1\-([^\.]+)\.html/', $input, $matches);
答案 1 :(得分:2)
$
是行尾标记。你需要把它放在正则表达式的末尾,也意味着你需要逃避它的文字.
。
preg_match('~"([0-9]+)/knownstring1-(.*?)\.html"$~'....
答案 2 :(得分: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 >
答案 3 :(得分: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
)