1

我有很多网址(字符串):

        $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';

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

    $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';
4

2 回答 2

3
$one = 'http://www.site.com/first/1/two/2/number/33/three/3';
$one = preg_replace('/\/number\/\d+/', '', $one);
echo $one;
于 2012-06-27T12:23:54.930 回答
0

我建议以下模式:

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

原因是:

  1. i修饰符将捕获 '/NumBer/42' 之类的url
  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
于 2012-06-27T16:33:18.737 回答