PHP: preg_replace replace abbreviation using backreferences
php, preg-replace, regex
Solution
The idea is to find all single letter + dot `\b[a-z]\.` followed by an other single letter + dot.
you can use:
$txt = preg_replace('~\b[a-z]\.(?=[a-z]\.)~i', '$0\,', $txt);
where `(?=..)` is a lookahead that performs only a check (followed by)
Second solution:
$txt = preg_replace('~(?<=\b[a-z]\.)(?=[a-z]\.)~i', '\,', $txt);
Instead of a backreference to the whole match, I use a lookbehind `(?<=..)`. Nothing is captured and the regex engine is at the good offset to add `\,`
Problem
I'd like to perform a character replacement using `preg_replace` in PHP on the following string: ``` Dieser Text enthält diverse Akürzungen wie z.B., d.h., u.a. oder m.w.H. ``` The output should be like: ``` Dieser Text enthält diverse Abkürzungen wie z.\,B., d.\,h., u.\,a. oder m.\,w.\,H. ``` Currently I'm using this code: ``` <?php $text = 'Dieser Text enthält diverse Akürzungen wie z.B., d.h., u.a. oder m.w.H.'; $searchFor = array( '/([a-z]\.)([a-z]\.)([a-z]\.)/i', // m.w.H. '/([a-z]\.)([a-z]\.)/i', // z.B. ); $replaceWith = array( '\1\\,\2\\,\3', '\1\\,\2', ); $replaced = preg_replace($searchFor, $replaceWith, $text); ?> ``` Is there a way to combine the two regular expressions? When I'm using the following expression, I'm not able to use the matched character: ``` /([a-z]\.){2,}/i ``` Any help is greatly appreciated.