我有一个包含加拿大地区字符串的数组,其格式如下:“region(province)”或“region - other region - other region(province)” 。在同一个字符串中可以有任意数量的区域组合在一起,用“ - ”分隔。我想从这些字符串中删除每个字符串中的最后一个空格,括号和省名,使其成为这种格式:“区域”或“区域 - 其他区域 - 其他区域”。删除总是相同模式的字符串的最后一部分
我怎么能用PHP中的正则表达式(或任何其他方法)来做到这一点?
我有一个包含加拿大地区字符串的数组,其格式如下:“region(province)”或“region - other region - other region(province)” 。在同一个字符串中可以有任意数量的区域组合在一起,用“ - ”分隔。我想从这些字符串中删除每个字符串中的最后一个空格,括号和省名,使其成为这种格式:“区域”或“区域 - 其他区域 - 其他区域”。删除总是相同模式的字符串的最后一部分
我怎么能用PHP中的正则表达式(或任何其他方法)来做到这一点?
试试这个:
$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;
}
,然后用它是这样的:
我常常发现,必须更容易使用比正则表达式的东西看,你也一样,因为你需要问。
这应该为你工作:
$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);
运行两个正则表达式的相同的字符串。
(运行每个全球更换和扩展)
这消除了省
发现:\([^()]* \)
取代:''
这将对分离的
发现:\h* - \h*
取代:' - '
可选,可以修剪开头和结尾的空白
发现:^\s+|\s+$
取代:''
查找RTRIM() – 2014-08-28 14:44:20
或者str_replace()函数可以工作 – 2014-08-28 14:46:20
关于' “(省)”'串 - - 目前还不清楚它可能出现或不出现,以及出现或不出现。 – Jon 2014-08-28 14:47:57