在某一段文字,我們有幾個鏈接,發現:preg_replace函數/的foreach改變網址的文字
$regex = '\b(http://www.domain.com/)[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]';
我們想改變這些URL到新的,如:
http://www.domain.com/news/item.php?ID=12321&TYPE=25成:/ news/page/$ arttype- $ artID/
$ url列出了其中幾個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);
}
有誰知道如何更新在$消息中找到的所有唯一的URL的?
-------使用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 ";
哦,世界發生了什麼事嗎?你知道這個腳本非常慢,因爲你已經在循環中放了幾個'preg_'。我會指出:** 1 - **表示您的正則表達式缺少分隔符,這意味着它是無效的。所以請啓用錯誤報告,這可以節省您的頭痛。 ** 2 - **您可以使用'preg_replace_callback()'一次完成所有這一切。 – HamZa
對不起。這是第一次與這個有幾場比賽等工作仍然沒有線索如何解決它,但:-) – KJS
@KJS正如'HamZa'指出,你缺乏分隔符。例如:'preg_match(「/ \ bweb \ b/i」'---在preg_math()'=> http://上查閱(取自)PHP手冊。 //php.net/manual/en/function.preg-match.php –