2012-09-05 96 views
1

請閱讀下面的代碼和註釋,看看我正在嘗試做什麼。很難在一段中解釋。PHP數組無法識別變量值

$url_fixx = 'home/sublink/group-view/product/catview1'; 
// What my variable holds. MY GOAL IS: I want to omit group-view, product and catview1 from this so I use the trick below. 

catview在其端部的隨機數,所以我使用下面的代碼以查找在端部的數量和它在這種情況下

$string = $url_fixx; 
$matches = array(); 
if (preg_match('#(catview\d+)$#', $string, $matches)) { 
    $catViewCatch = ($matches[1]); 
} 
// I got this from http://stackoverflow.com/a/1450969/1567428 

$url_fixx = str_replace(array('group-view/', 'product', 'catview1'), '', $url_fixx); 
// this outputs what I want. 

我的問題是輸出「catview1」:

//When I replace "catview1" with $catViewCatch, the whole str_replace doesnt work. 
$url_fixx = str_replace(array('group-view/', 'product', $catViewCatch), '', $url_fixx); 

這是爲什麼?我做錯了什麼?

PS:另外我的網址有時會變成這樣的東西。
$ url_fixx ='home/sublink/group-view/anotuer-sublink/123-article'

如何解決所有這些問題?

+0

是什麼'$ catViewCatch'包含您在使用捕捉它'preg_match'電話?另外,如果你的URL總是像這樣5個級別,爲什麼不在'/'字符上'爆炸',然後切掉數組的前2個元素? –

+0

@JonahBishop $ catViewCatch包含「catview1」,當我捕獲它使用preg_match。我不能使用爆炸,因爲URL可以改變。有時$ url_fixx ='home/sublink/group-view/anotuer-sublink/123-article'; – nasty

回答

3

這兩個例子都輸出完全一樣的東西。下面的代碼演示了這一點:

<?php 
$url_fixx = 'home/sublink/group-view/product/catview1'; 

$string = $url_fixx; 
$matches = array(); 
if (preg_match('#(catview\d+)$#', $string, $matches)) { 
    $catViewCatch = ($matches[1]); 
} 
echo str_replace(array('group-view/', 'product', 'catview1'), '', $url_fixx); 
echo '<br />'; 
echo str_replace(array('group-view/', 'product', $catViewCatch), '', $url_fixx); 
?> 

此外,您可以考慮使用preg_replace,而不是因爲它會完成任務用更少的代碼:

echo preg_replace('#group-view/product/catview[0-9]+#','',$url_fixx); 
+0

謝謝。我評論了約拿的回覆,說我的網址可以改變。如果我的網址像這樣改變$ url_fixx ='home/sublink/group-view/anotuer-sublink/123-article' – nasty

+0

你想要你的示例URL看起來如何?我無法理解格式以給你一個很好的答案。 – Brett

+0

我想要做的就是從我的網址中刪除所有「group-view」「product」和「catview [number]」值。而已。 – nasty