omg
omg

Reputation: 139862

How to trim out the space between non letters with PHP?

Say,should keep the space between letters(a-z,case insensitive) and remove the space between non-letters?

Upvotes: 0

Views: 322

Answers (2)

Inshallah
Inshallah

Reputation: 4814

This will strip any whitespace that is between two non-alpha characters:

preg_replace('/(?<![a-z])\s+(?![a-z])/i', '', $text);

This will strip any whitespace that has a non-alpha character on either side (big difference):

preg_replace('/(?<![a-z])\s+|\s+(?![a-z])/i', '', $text);

By using negative look-ahead and negative look-behind assertions, the beginning and end of the string are treated as non-alpha as well.

Upvotes: 1

KiNgMaR
KiNgMaR

Reputation: 1567

This should work:

$trimmed = preg_replace('~([a-z0-9])\s+([a-z0-9])~i', '\1\2', $your_text);

Upvotes: 3

Related Questions