Anka
Anka

Reputation: 35

Regex replace - Optional starting @ character

Currently I'm using /[^a-z0-9]/i together with PHP's preg_replace to get a new string with all chars which are NOT a-z A-Z 0-9 stripped out, so I'm left with a string containing only a-z A-Z 0-9.

My problem is that I now want the string to be able to contain an optional @-char as the first char in the string.

Examples:

@aåböc -> @abc

abcåäö1@23 -> abc123

How can I make this happen?

Thankful for any help with this. :)

Upvotes: 2

Views: 93

Answers (2)

Anirudha
Anirudha

Reputation: 32797

You can replace with this regex

/(?!^@)[^a-zA-Z\d]+/

with

empty string

Demo

Upvotes: 1

acdcjunior
acdcjunior

Reputation: 135762

Use the following regex:

/([^a-z0-9@]|(?<!^)@)/i

Inputs/Outputs:

@aåböc      -> @abc
abcåäö1@23  -> abc123

See demo code here.

Upvotes: 2

Related Questions