Serj Sagan
Serj Sagan

Reputation: 30218

Simple preg_replace regex that I can't figure out

I need a simple regex that will work in preg_replace that will convert any input given it to the following rules:

1) First character must be A-Z or a-z

2) If there is more than 1 character, then the following character(s) must be A-Z, a-z, 0-9 or a space

I need any non-conforming characters to be removed and the resultant string to be returned.

I have this as the regex string:

/^[a-zA-Z][a-zA-Z0-9 ]*$/

I have a little regex experience, so I assume this should work, but when I try a string like:

1Athsj294-djs

Here: http://www.functions-online.com/preg_replace.html

It is not working, please help. Thanks!

Upvotes: 2

Views: 727

Answers (3)

Rezigned
Rezigned

Reputation: 4932

I think your regex looks alright except you have to remove ^ and $

So it should be

preg_match('/[a-zA-Z][a-zA-Z0-9 ]*/', $subject)           // this is for preg_match though
preg_replace('/[^a-zA-Z]*([a-zA-Z][a-zA-Z0-9]*)[^a-zA-Z0-9]*/', '$1', '1Athsj294-djs') // for preg_replace

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336198

$result = preg_replace('/^[^a-z]*([a-z][a-z0-9 ]*).*$/si', '\1', $subject);

changes

1Athsj294-djs

into

Athsj294

Explanation:

^            # Start of string
[^a-z]*      # Match (optionally) any characters except ASCII letters
(            # Match and capture...
 [a-z]       #  one ASCII letter
 [a-z0-9 ]*  #  zero or more ASCII letters/digits or spaces
)            # End of capturing group
.*           # Match the rest of the string
$            # Match the end of the string

The /si modifiers make the regex case-insensitive and allow the dot to match newlines.

Upvotes: 2

chx
chx

Reputation: 11760

Well, you can capture preg_match('/^[a-zA-Z][a-zA-Z0-9 ]*/', $string, $matches) for example and $matches[0] will contain your match. If you want to actually preg_replace that requires lookahead.

Upvotes: 0

Related Questions