RegEx替换为条件:仅分隔相邻的数字

时间:2012-05-23 18:44:36

标签: php regex

我有一个带有数字的txt文件:

1-2 c., 3-6 c., 7-8 c., 12-15 c. etc. 

我需要将相邻的数字(示例中的1-2和7-8)与“和”分开,而其他数字我想要原样保留,以便我得到这个:

1 and 2 c., 3-6 c., 7 and 8 c., 12-15 c. etc.

如果我想替换所有连字符,我可以这样做:     

$newtxt = preg_replace('#(\d+)-(\d+)#', '$1 and $2', $txt);

我可以使用PHP的其他方法轻松完成,但问题是我需要在正则表达式的帮助下才能做到这一点。这可能吗?

2 个答案:

答案 0 :(得分:1)

您可以使用preg_replace_callback并使用该功能。它不是完全正则表达式,而是接近它。

function myCallback ($match){
   if($match[1] == $match[2]-1){
       return $match[1]." and ".$match[2];
   } else {
       return $match[0];
   }
}
preg_replace_callback(
    '#(\d+)-(\d+)#',"myCallback",$txt
);

希望它有所帮助。

答案 1 :(得分:0)

您需要preg_replace_callback,这将允许您编写一个函数,该函数根据匹配和捕获的字符串返回所需的替换字符串。

$str = '1-2 c., 3-6 c., 7-8 c., 12-15 c. etc. ';

$str = preg_replace_callback(
  '/(\d+)-(\d+)/',
  function($match) {
    return $match[2] == $match[1] + 1 ? "$match[1] and $match[2]" : $match[0];
  },
  $str
);

echo $str;

<强>输出

1 and 2 c., 3-6 c., 7 and 8 c., 12-15 c. etc.