Search code examples
phpstringpreg-replacepreg-matchstr-replace

How to remove spaces in a string using preg_replace


I am to remove the spaces between the initials and keep the space between initial and any word.

I would like to get this result. A.J.P. Jane B.V.

Instead I am getting this result A.J. P. Jane B. V.

$string = "A.J. P. Jane B. V.";

$string =  preg_replace('/\.\s\[A-z]{1}\./', '.', $string);

echo $string;

Solution

  • Use this rule \.\s([A-Z]{1})\. or \.\s([A-Z])\. without explicit limit to match [dot][space][letter][dot] and
    replace with .$1., [dot][letter][dot]

    $string =  preg_replace('#\.\s([A-Z]{1})\.#', '.$1.', $string);
    
    echo $string;
    

    Will output

    A.J.P. Jane B.V.