Search code examples
phpregexpreg-replacepreg-matchstr-replace

How can I place a dot after each character using preg replace


The purpose of this code is to find independent characters and place a dot after each character. eg. "Jane Doe L D I" should return "Jane Doe L. D. I."

My code works under certain conditions. However, when I use the following scenarios it fails. It fails when I use a string of "Jeans Shirts K/N" and returns "Jeans Shirts K./N."

$string = "Jeans Shirts K-92";  
echo preg_replace('/\b[A-z]{1}\b/', '$0.', $string);   

Result: (Fail)   
Jeans Shirts K.-92

Expected Result:
Jeans Shirts K-92

Solution

  • You should use:

    echo preg_replace('/(?<=\s|^)[A-Za-z](?=\s|$)/', '$0.', $string);
    //=> Jeans Shirts K-92
    

    [A-z] is incorrect as it matches many more character between ASCII A (65) and z (122).