2012-04-26 54 views
0

排除名「.html」我使用下面的preg_replace()調用替換爲新的結構鏈接:的preg_replace從替代條款

preg_replace('/example.com\/sub-dir\/(.*)">/', 'newsite.co.uk/sub-dir/$1.html">', $links); 

它幾乎工作,但它不會對加名「.html」去年底更換,所以它最終成爲類似‘newsite.co.uk/sub-dir/page-identifier’,而不是「newsite.co.uk/sub-dir/page-identifier。 HTML」。

我相信這是一些簡單的我失蹤,但谷歌搜索的問題並沒有拿出任何有用的結果,所以我希望這裏有人能幫助!

在此先感謝!

編輯:作爲一個例子,這裏是$鏈接側連接

<a href="http://example.com/sub-dir/the-identifier">Anchor</a> 

上面的例子,如果工作我改變了REGEXT但是到下面沒有(*):

<a class="prodCatThumb" title="View product" href="http://example.com/sub-dir/product-identifier"> 

它結束了作爲

<a class="prodCatThumb.html" title="View product" href="http://example.com/sub-dir/product-identifier"> 

任何想法?

+0

你能告訴我們'$ links'的內容是什麼? – anubhava 2012-04-26 11:51:42

+0

@Ashley:請看看我的編輯,因爲我爲你解決了這個問題 – Nikola 2012-04-26 12:26:14

回答

2

是的,它是關於.*
只需添加?到像這樣:.*?

例如:

<?php 
    $links = "example.com/sub-dir/myfile.php"; 
    $links = preg_replace('/example.com\/sub-dir\/(.*?)/', 'newsite.co.uk/sub-dir/$1.html', $links); 
    echo $links; 
?> 

編輯: @Ashley:肯定的是,問號使得前面的令牌在正則表達式中可選。例如: - colou·R顏色和顏色相匹配(從this link)。

但是,additionaly當你使用它?它的ungready方法(這可能有助於解釋:Regular expression with .*? (dot-star-questionmark) matches too much?或本:http://www.phpro.org/tutorials/Introduction-to-PHP-Regex.html

因此,要回答你的QQ:

<?php 
    $links = '<a class="prodCatThumb" title="View product" href="example.com/sub-dir/product-identifier">'; 
    $links = preg_replace('/example.com\/sub-dir\/(.*?)"/', 'newsite.co.uk/sub-dir/$1.html"', $links); 
    echo $links; 
?> 

輸出此鏈接:
<a class="prodCatThumb" title="View product" href="example.com/sub-dir/product-identifier">
現在會是:
<a class="prodCatThumb" title="View product" href="newsite.co.uk/sub-dir/product-identifier.html">

+0

這工作!你能解釋一下什麼是「?」爲什麼它修復它,所以我知道在未來?再次感謝! – Ashley 2012-04-26 11:56:58

+0

@Nikolo這不太合適......如果標記是「 「它結束爲」」不知何故! – Ashley 2012-04-26 12:12:02

+0

@Ashley:我編輯了我的答案,因爲這裏不適合 – Nikola 2012-04-26 12:19:44

0

爲了更好地理解問題,我們需要查看$links的內容。

同時,你可以嘗試:

preg_replace('#example\.com/sub-dir/([^"]*)">#', 
      'newsite.co.uk/sub-dir/$1.html">', $links); 
+0

謝謝,你的正則表達式適用於我的帖子中的第一個例子,但第二個例子根本沒有改變鏈接! – Ashley 2012-04-26 12:16:41

+0

其實它適用於你的兩個例子。如果你想,我也可以給你一個在線演示。 – anubhava 2012-04-26 12:24:24

+0

下面是現場演示:http://ideone.com/X05oM – anubhava 2012-04-26 12:27:47

0

我只是用this testing page檢查你的正則表達式,它正常工作與您所提供的示例文本(<a href="http://example.com/sub-dir/the-identifier">Anchor</a>)。你確定沒有別的東西會給你造成問題嗎?

測試現場返回此:<a href="http://newsite.co.uk/sub-dir/the-identifier.html">Anchor</a>

+0

謝謝,請檢查原始帖子以獲取更新示例。 – Ashley 2012-04-26 12:14:35