2014-09-30 83 views
0

我有一個字符串http://localhost:9000/category,我想替換爲category.html,即剝離/category之前的所有內容,並添加.html用通配符替換字符串

但是找不到用str_replace做到這一點的方法。使用替代

回答

1

preg_replacestr_replace

正則表達式:

.*\/(.+) 

替換字符串:

$1.html 

DEMO

$input = "http://localhost:9000/category"; 
echo preg_replace("~.*/(.+)~", '$1.html', $input) 

輸出:通過$1.html。看到演示

category.html 
+0

應該像'〜* /([^ /] +)[/]〜'相反,以防萬一我們也想使用'http:// localhost:9000/test/category/q /'。如果他不這樣做,你的正則表達式真的很棒! – 2014-09-30 11:28:50

+0

只是'/?'就夠了。如果我的意圖是我應該更新我的答案...... – 2014-09-30 11:40:52

+0

實際上,它會的,但OP沒有說以'/'結尾的任何內容。我發佈了一個答案,假設輸入將以'/'結尾,但我正在改變它來解決'問題'。 – 2014-09-30 11:43:18

3

你想在這種情況下使用parse_url

$parts = parse_url($url); 
$file = $parts['path'].'.html'; 

或沿這條線的東西。嘗試一下它。

伊斯梅爾·米格爾認爲這個較短的版本,我喜歡它:

$file = parse_url($url,PHP_URL_PATH).'.html'; 

^*!$(\*)+正則表達式好多了。

+0

'parse_url'在這裏不起作用。它用於從結構爲' = [& = ] ...'的字符串獲取值,並創建名稱爲「」或數組的變量。檢查這裏:http://php.net/manual/en/function.parse-str.php – 2014-09-30 11:38:18

+0

無視我的評論:/你是對的。我讀了'parse_str'。 :/ – 2014-09-30 11:52:01

+0

你可以請編輯(添加一個空間或東西),所以我可以upvote? – 2014-09-30 11:58:28

0

溶液正則表達式:

<?php 
    $url = 'http://localhost:9000/category'; 
    echo @end(explode('/',$url)).'.html'; 
?> 

此分割字符串,並獲得最後一部分,並附加.html

注意,這將在輸入與/(如:$url = 'http://localhost:9000/category/';)結束不工作

另外請注意,這依賴於不規範的行爲,並可以很容易地改變,這只是製作成需要一行代碼。您可以改爲製作$parts=explode([...]); echo end($parts).'.html';

如果輸入與/偶爾結束,我們可以這樣做,以避免出現問題:?

<?php 
    $url = 'http://localhost:9000/category/'; 
    echo @end(explode('/',rtrim($url,'/'))).'.html'; 
?>