[英]PHP (URL) matching regex issue
I'm looking for a regex to match a given url wich contains something like 我正在寻找一个正则表达式来匹配给定的URL,其中包含类似
"/unknownnumber/knownstring1-unknownstring.html"
in order to redirect it with PHP to other new url like 为了用PHP将其重定向到其他新网址,例如
"/unknownnumber/knownstring2-unknownstring"
to keep google indexed urls active. 使Google索引网址保持活动状态。
I have used next statement, but $do_match
returns 0
, so I'm doing something wrong... 我使用了next语句,但是
$do_match
返回0
,所以我做错了...
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: 如果'unknownumber'是字符串的数字部分,则regexp模式如下所示:
$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: print_r输出:
Array
(
[0] => /123/knownstring1-unknownstring.html
[1] => 123
[2] => knownstring1
[3] => unknownstring
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.