Works for a Living
Works for a Living

Reputation: 1293

preg_replace Strip Dashes from Alpha Characters (Preserve between Numbers)

How can I remove all dashes between Letters, but preserve any dashes in between Numbers? Sorry I don't have any previous attempts to display, because I haven't been able to find anything for this after an hour of googling. Currently I'm using a simple str_replace to remove unwanted characters.

Upvotes: 1

Views: 92

Answers (2)

user557597
user557597

Reputation:

If you just are interested in Letter-Letter, this might work
If you use anything other than [a-zA-z] or \pL, you will be removing
the dash between letters, punctuation, whitespace, control chars, or any combination, etc...

Find: (?i)(?<=[a-z])-(?=[a-z])
Replace with empty string.

Upvotes: 1

anubhava
anubhava

Reputation: 785196

You can use lookheads for this:

$str = preg_replace('/(?<=\D)-(?=\D)/', '', 'abc-xyz-12-45-89');
//=> abcxyz-12-45-89

Upvotes: 1

Related Questions