2012-06-27 45 views
1

删除文本我有很多的url(字符串):从字符串/ URL

 $one = 'http://www.site.com/first/1/two/2/three/3/number/342'; 
     $two = '/first/1/two/2/number/32'; 
     $three = 'site.com/first/1/three/3/number/7'; 
     $four = 'http://www.site.com/first/13/two/2/three/33/number/33/four/23'; 

如何删除这个变量/数量/ X用PHP? 我的例子应该是:

$one = 'http://www.site.com/first/1/two/2/three/3'; 
    $two = '/first/1/two/2'; 
    $three = 'site.com/first/1/three/3'; 
    $four = 'http://www.site.com/first/13/two/2/three/33/four/23'; 

回答

3
$one = 'http://www.site.com/first/1/two/2/number/33/three/3'; 
$one = preg_replace('/\/number\/\d+/', '', $one); 
echo $one; 
0

我建议以下模式:

'@/number/[0-9]{1,}@i' 

的原因是:

  1. i修改将赶上像URL '/ NumBer/42'
  2. 使用@分隔模式可以创建更具可读性的模式,并减少需要转义斜线(例如, \/\d+
  3. 尽管[0-9]{1,}\d+更详细,但它具有更多意图显示的附加好处。

下面是它的一个演示的用法:

<?php 

$urls[] = 'http://www.site.com/first/1/two/2/three/3/number/342'; 
$urls[] = '/first/1/two/2/number/32'; 
$urls[] = 'site.com/first/1/three/3/number/7'; 
$urls[] = 'http://www.site.com/first/13/two/2/three/33/number/33/four/23'; 
$urls[] = '/first/1/Number/55/two/2/number/32'; 

$actual = array_map(function($url){ 
    return preg_replace('@/number/[0-9]{1,}@i', '', $url); 
}, $urls); 

$expected = array(
    'http://www.site.com/first/1/two/2/three/3', 
    '/first/1/two/2', 
    'site.com/first/1/three/3', 
    'http://www.site.com/first/13/two/2/three/33/four/23', 
    '/first/1/two/2' 
); 

assert($expected === $actual); // true