我有很多网址(字符串):
$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';
答案 0 :(得分:3)
$one = 'http://www.site.com/first/1/two/2/number/33/three/3';
$one = preg_replace('/\/number\/\d+/', '', $one);
echo $one;
答案 1 :(得分:0)
我建议采用以下模式:
'@/number/[0-9]{1,}@i'
原因是:
i
修饰符会捕获“/ NumBer / 42”@
分隔模式可以获得更易读的模式并减少转义斜杠的需要(例如\/\d+
)[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