【问题标题】:Php - parsing url to friendly (Using regexp)Php - 将 url 解析为友好(使用正则表达式)
【发布时间】:2014-09-18 10:56:20
【问题描述】:
使用正则表达式我需要转换这个string url。
<a class="navPages" href="?mode=author&id=9&word=friend&fn=%d">%s</a>
要获得这样的输出格式:
<a class="navPages" href="author/9/friend/page/%d>%s</a>
或者得到结果:
0:autor
1:9
2:friend
3:%d
我应该如何编写正则表达式?
【问题讨论】:
标签:
php
regex
friendly-url
【解决方案1】:
这是一个完整的解决方案,包含 2 个表达式(一个用于获取 URL,一个用于拆分链接):
$link = '<a class="navPages" href="?mode=author&id=9&word=friend&fn=%d">%s</a>';
// extract the URL
preg_match('/href="([^"s]+)"/', $link, $link_match);
$url = $link_match[1];
// build the new URL and HTML link
preg_match_all('/([^\s&?=]+)=?([^\s&?=]+)?/', $url, $url_match);
$new_url = '';
foreach ($url_match[2] as $value)
$new_url .= $value . '/';
$new_url = substr($new_url, 0, -1);
$new_link = '<a class="navPages" href="' . $new_url . '>%s</a>';
echo $new_link; // Output: <a class="navPages" href="author/9/friend/%d>%s</a>
【解决方案2】:
将(& 或 ?)和 = 之间的所有内容替换为 /:
$link = preg_replace("/[&?][^=]*=/", "/", $link);
结果:
author/9/friend/%d
要获取数组中的部分,请使用与preg_split 相同的正则表达式:
$parts = preg_split("/[&?][^=]*=/", $link);
注意,使用这种方法,第一个元素将为空——结果:
array(5) {
[0]=> ""
[1]=> "author"
[2]=> "9"
[3]=> "friend"
[4]=> "%d"
}
【解决方案3】:
试试这样的:
$txt = '<a class="navPages" href="?mode=author&id=9&word=friend&fn=%d">%s</a>';
preg_match('/^<a.*?href=(["\'])(.*?)\1.*$/', $txt, $patterns);
$data = explode('=',$patterns[2]);
$my_array=array();
foreach ($data as $key => $value) {
$test[] = explode('&', $value);
$my_array[]=$test[$key][0];
unset($my_array[0]);
}
输出
Array
(
[1] => author
[2] => 9
[3] => friend
[4] => %d
)
然后使用implode 获取您的href。