2

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);
user2635901
  • 203
  • 2
  • 12
  • well, it looks like you want to add a `.` after Upper Case letters with a space afterward, right? If you can state your exact desired result that would be good. Otherwise, it looks like the answer you would want should spit out: `J.o.h.n. .D.o.e. .l... .r. .t.` – Fallenreaper Jan 18 '16 at 13:29
  • the desired result is John Doe L. R. T. – user2635901 Jan 18 '16 at 13:40
  • Could also try `preg_replace_callback('/(?<=\s)([A-Za-z])(?:\.|\b)/', function ($matches) { return strtoupper($matches[1] . ".");` and drop second replace if you don't need to check for the first boundary. [See demo at eval.in](https://eval.in/503945). Further be aware, that `[A-z]` [matches more than \[a-zA-Z\]](http://stackoverflow.com/questions/4923380/difference-between-regex-a-z-and-a-za-z) but that's not the actual problem. – bobble bubble Jan 18 '16 at 15:28

2 Answers2

0

Try matching the letters that are surrounded by spaces, or by a space at the beginning and then, the end of the text:

echo preg_replace("/\s([a-zA-Z])\s|$/", "$1.", $input_lines);
Aferrercrafter
  • 319
  • 1
  • 6
  • 14
0

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);
Ravi Hirani
  • 6,511
  • 1
  • 27
  • 42