删除总是相同模式的字符串的最后一部分


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

我有一个数组,其中包含加拿大的区域字符串,语法如下:"region(province)"或"region-other region-other region(province)"。在同一字符串中,可以有任意数量的区域组合在一起,用"-"分隔。我想从这些字符串中删除每个字符串中的最后一个空格、括号和省份名称,改为以下格式:"region"或"region-otherregion-other region"。

如何使用PHP中的regex(或任何其他方法)来实现这一点?

试试这个:

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

为什么不创建这样一个简单的函数?

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;
}

然后以这种方式使用:

$data = str_before($data,' (');

我经常发现这一定比regex的东西更容易阅读,你也是,因为你需要问。

这应该适用于您:

$value = 'region - other region - other region (province)';
$result = substr($value, 0, strrpos( $value, ' '));
echo $result;

这将与相呼应

region - other region - other region

或者使用循环,您可以执行以下操作:

$value = array('region - other region - other region (province)');
foreach($value as &$v)
{
    $v = substr($v, 0, strrpos( $v, ' '));
}
print_r($value);

哪个会打印这个:

Array ( [0] => region - other region - other region )

由于preg_replace在数组上工作,如何:

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

在同一字符串上运行两个正则表达式
(每个作为全局替换和扩展运行)

  1. 这将删除省份的
    查找:'( [^()]* ')
    替换:''

  2. 此设置分隔符的格式
    查找:'h* - 'h*
    替换:' - '

  3. 可选,可以修剪前导和尾部空白
    查找:^'s+|'s+$
    替换:''