我有一个包含数字的txt文件:
1-2 c., 3-6 c., 7-8 c., 12-15 c. etc.
我需要用“and”分隔相邻的数字(在本例中是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的其他方法很容易做到这一点,但问题是我只需要在正则表达式的帮助下做到这一点。这有可能吗?
发布于 2012-05-24 03:08:00
您需要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.
发布于 2012-05-24 03:02:40
您可以使用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
);
希望能有所帮助。
https://stackoverflow.com/questions/10725990
复制相似问题