Ben Shoval
Ben Shoval

Reputation: 1750

How to insert period after qualifying capitalized letters?

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:

  1. It is the followed by a space; or
  2. It is followed by another capitalized letter; or
  3. It the last letter in the string and preceded by a space or capitalized letter

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

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

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

Picard
Picard

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

anubhava
anubhava

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);

RegEx Demo

Although this regex is more complex than Casimir's simpler regex

Upvotes: 1

Related Questions