Reputation: 1385
I have a txt file with numbers:
1-2 c., 3-6 c., 7-8 c., 12-15 c. etc.
I need to separate adjacent numbers (1-2 and 7-8 in the example) with " and " while the rest of the numbers I want to leave as they are, so that I get this:
1 and 2 c., 3-6 c., 7 and 8 c., 12-15 c. etc.
If I wanted to replace all of the hyphens I could do that like this:
$newtxt = preg_replace('#(\d+)-(\d+)#', '$1 and $2', $txt);
I can do it easily with other means of PHP, but the problem is that I need to do that with the help of regular expressions only. Is that possible?
Upvotes: 0
Views: 200
Reputation: 126742
You need preg_replace_callback
which will allow you to write a function that returns the required replacement string depending on the matched and captured strings.
$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;
output
1 and 2 c., 3-6 c., 7 and 8 c., 12-15 c. etc.
Upvotes: 0
Reputation: 2253
You can use preg_replace_callback and use the function. It is not fully regexp but close to it.
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
);
Hope it helps.
Upvotes: 1