Search code examples
phpregexpreg-replacepreg-matchstr-replace

How can I match characters in a string and palce a dot after each Letter using preg replace


My code works. However I would like it to return the result below.

John Doe L. R. T.

Instead it returns (It only behaves like this when it finds 2 or more dots.) John Doe L.. r T.

$string = "John Doe l. r t";

$string = preg_replace_callback('/\b\s[A-z]{1}\b/', function ($matches) {
  return strtoupper($matches[0]);
}, $string);

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

Solution

  • I have made some modifications in your code.

    Try this code:-

    $string = "John Doe l. r t";
    
    $string = preg_replace_callback('/\b\s[A-z]{1}\b/', function ($matches) {
     return strtoupper($matches[0]);
    }, str_replace('.', '', $string));
    
    echo preg_replace('/\b\s[A-z]{1}\b/', '$0.', $string);