在一段文字中,我们有几个链接,可以找到:
$regex = '\b(http://www.domain.com/)[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]';
我们希望将这些网址更改为新网址,例如:
http://www.domain.com/news/item.php?ID=12321&TYPE=25进入:/ news / page / $ arttype- $ artID /
$ url列出了其中几个网址,但我们似乎无法在$ message中更新它们。
这是到目前为止的代码:
$string = "$message";
function do_reg($text, $regex) {
preg_match_all($regex, $text, $result, PREG_PATTERN_ORDER);
return $result[0];
}
$A =do_reg($string, $regex);
foreach($A as $url) {
$check = parse_url($url, PHP_URL_QUERY);
preg_match("/ID=([^&]+)/i", $check, $matches);
$artID = $matches[1];
preg_match("/TYPE=([^&]+)/i", $check, $matches);
$arttype = $matches[1];
preg_replace("$url", "/news/page/$arttype-$artID/", $text);
}
有谁知道如何更新$ message中找到的所有唯一网址?
-------使用V-tech的代码----------------
$message = "
<li><strong><a href="http://www.domain.com/news/item.php?ID=12321&TYPE=25" target="_blank">Link 1</a></li>
<li><strong></strong><a href="http://www.domain.com/news/item.php?ID=12300&TYPE=2" target="_blank">Link 2</a></li>
<li><a href="http://www.domain.com/news/item.php?ID=12304&TYPE=2" target="_blank">Link 3</a></li>
<li><a href="http://www.domain.com/news/item.php?ID=12314&TYPE=2" target="_blank">Link 4</a></li>";
$pattern = "/(http:\/\/www\.domain\.com)\/news\/item\.php\?ID=([^&]+)&TYPE=(\d+)/g";
$replacement = "\${1}/news/page/\${2}-\${3}/";
preg_replace($pattern, $replacement, $message);
echo "$message ";
答案 0 :(得分:1)
用一个命令做什么呢?
$pattern = "/(http:\/\/www\.domain\.com)\/news\/item\.php\?ID=([^&]+)&TYPE=(\d+)/";
$replacement = "\${1}/news/page/\${2}-\${3}/";
$result = preg_replace($pattern, $replacement, $message);
基本上,它会删除三条信息(scheme:// domain,ID value和TYPE value),并通过将这三个部分插入$ replacement字符串来烹饪新的URL。
ID=([^&]+)&TYPE=(\d+)
假设,ID值可以是任何东西(小心以&amp;开头的html实体)直到&amp ;.这里的TYPE值假定为数值。所以根据你的需要改变它。
更新了:从$ pattern中移除了g标志,将preg_replace()结果放入$ result
答案 1 :(得分:1)
From : http://www.domain.com/news/item.php?ID=12321&TYPE=25
To : http://www.domain.com/news/page/25-12321/
$string_start = '<li><strong><a href="http://www.domain.com/news/item.php?ID=12321&TYPE=25" target="_blank">Link 1</a></li>
<li><strong></strong><a href="http://www.domain.com/news/item.php?ID=12300&TYPE=2" target="_blank">Link 2</a></li>
<li><a href="http://www.domain.com/news/item.php?ID=12304&TYPE=2" target="_blank">Link 3</a></li>
<li><a href="http://www.domain.com/news/item.php?ID=12314&TYPE=2" target="_blank">Link 4</a></li>';
$string_end = $string_start;
$string_end = preg_replace("/(https|http):\/\/(w{0,3}\.{0,1})(domain\.com)\/news\/item\.php\?ID=([0-9]*)(&|&)TYPE=([0-9]*)/", "$1://$2$3/news/page/$6-$4/", $string_end);