Reputation: 1750
How can I insert a period after any capitalized single letter that is not already followed by a capital letter according to the following rules:
Sample Inputs/Outputs:
Patrick TJ Stephens
becomes Patrick T.J. Stephens
TJ Stephens
becomes T.J. Stephens
TJ Stephens QC
becomes T.J. Stephens Q.C.
Marissa C J Gilbert
becomes Marissa C. J. Gilbert
Marissa C Gilbert
becomes Marissa C. Gilbert
C Marissa Gilbert
becomes C. Marissa Gilbert
Marissa Gilbert C
becomes Marissa Gilbert C.
I've been using:
$str = preg_replace( '/([A-Z])(?=\s|$)/', '\1.', $str );
Unfortunately, it turns Patrick TJ Stephens
into Patrick TJ. Stephens
instead of Patrick T.J. Stephens
.
Upvotes: 1
Views: 62
Reputation: 89557
You can use:
$str = preg_replace('/[A-Z](?![a-z.])\K/', '.', $str);
Not sure it follows your rules but it does the job.
or with this one: [A-Z](?![^A-Z\s])\K
Upvotes: 0
Reputation: 4112
And a version for dummies, by dummy me :)
$str = preg_replace(
array(
'/([A-Z])(?=\s|$)/',
'/([A-Z])([A-Z])/'
),
array(
'\1.',
'\1.\2'
),
$str );
Here's the demo
Upvotes: 0
Reputation: 785246
Translating all your requirements will need a lookahead and lookbehind as this regex:
$str = preg_replace('/(?<=[\hA-Z])[A-Z]$|[A-Z](?=[\hA-Z])/m', '$0.', $str);
Although this regex is more complex than Casimir's simpler regex
Upvotes: 1