簡體   English   中英

用另一個地址替換http://www.***的所有實例

[英]Replace all instances of http://www.*** with another address

我有一個字符串,其中包含一個網站上的幾個鏈接,但是我需要更改它們以鏈接到另一個網站。

例如, http://www.site2.com/contacthttp://www.site3.com/contact必須成為http://www.mainsite.com/contact URL的此處和/contact只是示例,現實是我需要找到http://所有實例,並用新的URL替換該URL與next /之間的內容。

我有辦法通過preg_replace()做到這一點(如果在最佳選擇中也是如此)?

更新:該答案不能反映問題,因為該問題首先會引起誤解。 看看Jeroens或ShogunArts.des答案

無需正則表達式

$string = str_replace(
  array('http://www.site2.com/','http://www.site3.com/'),
  'http://www.mainsite.com/',
  $string
);

str_replace()

  1. 匹配網址: http : //daringfireball.net/2010/07/improved_regex_for_matching_urls
  2. 在回調函數中使用preg_replace_callback()
    1. 使用parse_url()獲取所有部分
    2. host部分替換為mainsite.com

這樣的事情應該做到:

$pattern = '#(http://)([a-z0-9.-])+/+([a-z0-9.-])#i';
$oldurl = 'http://www.site2.com/contact';
$replacement = '$1www.mainsite.com/$3';

$newurl = preg_replace($pattern, $replacement, $oldurl);

編輯:

$string = 'String with many URLs';

echo replaceUrls($string);

function replaceUrls($string) {
    $pattern = '#(http://)([a-z0-9.-])+/+([a-z0-9.-]|)#i';
    $replacement = '$1www.mainsite.com/$3'; 

    return preg_replace($pattern, $replacement, $string); 
}

用新站點名稱替換正則表達式(?<=http://)(www\\.site2\\.com)(?=/contact)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM