Reputation: 1163
I have an array containing string of regions in Canada that follows this syntax: "region (province)" or "region - other region - other region (province)". There can be any number of regions grouped together separated by " - " in a same string. I would like to trim the last space in each string, the parenthesis and the province name from those strings, making them in this format instead: "region" or "region - other region - other region".
How could I do this with a regex (or any other method) in PHP?
Upvotes: 1
Views: 74
Reputation:
Run two regex on same string.
(run each as global replace and expanded)
This removes provinces'
find: \( [^()]* \)
replace: ''
This formats separator's
find: \h* - \h*
replace: ' - '
Optional, can trim leading and trailing whitespace
find: ^\s+|\s+$
replace: ''
Upvotes: 1
Reputation: 91415
As preg_replace works on array, how about:
$array = preg_replace('/\s+\(.+$/', '', $array);
Upvotes: 1
Reputation: 4696
This should work for you:
$value = 'region - other region - other region (province)';
$result = substr($value, 0, strrpos( $value, ' '));
echo $result;
This would echo
region - other region - other region
Alternatively using a loop you could do the following:
$value = array('region - other region - other region (province)');
foreach($value as &$v)
{
$v = substr($v, 0, strrpos( $v, ' '));
}
print_r($value);
Which would print this:
Array ( [0] => region - other region - other region )
Upvotes: 1
Reputation: 16688
Why not create a simple function like this?
function str_before($haystack,$needle)
// returns part of haystack string before the first occurrence of needle.
{
$pos = strpos($haystack,$needle);
return ($pos !== FALSE) ? substr($haystack,0,$pos) : $haystack;
}
And then use it this way:
$data = str_before($data,' (');
I often find that must easier to read than regex things, and you too, since you need to ask.
Upvotes: 1
Reputation: 64
Try this:
$string = array();
$string[] = "region - other region - other region (province)";
foreach ($string as $str){
echo trim(preg_replace('/(\(.*\))$/','', $str));
}
Upvotes: 1