Php 从字符串/url中删除文本
我有许多URL(字符串): 如何使用PHP删除此变量的/number/x? 例如:Php 从字符串/url中删除文本,php,regex,Php,Regex,我有许多URL(字符串): 如何使用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'; 我建议采取以下模式: '@/
$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';
我建议采取以下模式:
'@/number/[0-9]{1,}@i'
原因如下:
<?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
i
修饰符将捕获像“/NumBer/42”这样的URL@
对模式进行定界有助于形成更具可读性的模式,并减少对斜杠的转义(例如\/\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
<?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