2012-09-05 93 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