Search code examples
phptypographypunctuation

How to replace (.) dots by (·) interpuncts in PHP?


There's a French typographic rule to write properly some words in a genderless way, by adding an (·) interpunct between letters. A few authors on my website are however typing a simple (.) dot instead.

As a solution, I'd like to create a function to replace in PHP strings each dots which are placed between two lowercase letters by interpuncts. But my PHP skills are rather limited… Here is what I'm looking for:

REPLACE THIS:

$string = "T.N.T.: Chargé.e des livreur.se.s."

BY THIS:

$string = "T.N.T.: Chargé·e des livreur·se·s."

Could someone help me please? Thank you.


Solution

  • Use the preg_replace with pattern to dynamically match 3 groups - two lowercase letters (including special French letters) and dot between, and use the first and third captured group in replacement, along with intepunct:

    $string = "T.N.T.: Chargé.e des livreur.se.s.";
    $pattern = '/([a-zàâçéèêëîïôûùüÿñæœ])(\.)([a-zàâçéèêëîïôûùüÿñæœ])/';
    $replacement = '$1·$3'; //captured first and third group, and interpunct in the middle 
    
    //results in "T.N.T.: Chargé·e des livreur·se·s."
    $string_replaced = preg_replace($pattern, $replacement, $string); 
    

    More about preg_replace:

    https://www.php.net/manual/en/function.preg-replace.php