user2635901
user2635901

Reputation: 223

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;

Upvotes: 1

Views: 2120

Answers (2)

Alex Andrei
Alex Andrei

Reputation: 7283

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.

Upvotes: 2

monirz
monirz

Reputation: 544

Try this,

$string = preg_replace('/\s+/', '', $string);

Upvotes: 0

Related Questions