Choub890
Choub890

Reputation: 1163

Removing the last part of a string which is always the same pattern

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

Answers (5)

user557597
user557597

Reputation:

Run two regex on same string.
(run each as global replace and expanded)

  1. This removes provinces'
    find: \( [^()]* \)
    replace: ''

  2. This formats separator's
    find: \h* - \h*
    replace: ' - '

  3. Optional, can trim leading and trailing whitespace
    find: ^\s+|\s+$
    replace: ''

Upvotes: 1

Toto
Toto

Reputation: 91415

As preg_replace works on array, how about:

$array = preg_replace('/\s+\(.+$/', '', $array);

Upvotes: 1

The Humble Rat
The Humble Rat

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

KIKO Software
KIKO Software

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

Alex Montoanelli
Alex Montoanelli

Reputation: 64

Try this:

$string = array();
$string[] = "region - other region - other region (province)";
foreach ($string as $str){
    echo trim(preg_replace('/(\(.*\))$/','', $str));
}

Upvotes: 1

Related Questions