Reputation: 13
i have many urls(string):
$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';
how can i remove for this variables /number/x with PHP? for my examples should be:
$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';
Upvotes: 1
Views: 344
Reputation: 7204
I would suggest the following pattern:
'@/number/[0-9]{1,}@i'
The reasons are:
i
modifier will catch urls like '/NumBer/42'@
to delimit the pattern makes for a much more readable pattern and mitigates the need to escape slashes (e.g. \/\d+
)[0-9]{1,}
is more verbose than \d+
, it has the added benefit of being much more intention revealing.Below is a demo of it's usage:
<?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
Upvotes: 0
Reputation: 22592
$one = 'http://www.site.com/first/1/two/2/number/33/three/3';
$one = preg_replace('/\/number\/\d+/', '', $one);
echo $one;
Upvotes: 3