Satish
Satish

Reputation: 1335

Validate that a string contains only space-delimited alphanumeric words which do not start with a digit

I want to use preg_match() such that there should not be special characters such as @#$%^&/ ' in a given string.

For example :

I tried but could not reach to a valid answer.

Upvotes: 5

Views: 360

Answers (4)

mickmackusa
mickmackusa

Reputation: 48091

To validate that a string contains one or more alphanumeric words (each not starting with a digit), use a repeatable subpattern to match an optional space before matching a letter, then zero or more alphanumeric characters. Use a lookbehind to ensure that a space is not immediately at the start of the string. Use ^ and $ anchors to ensure the entire string qualifies.

Code: (Demo)

if (preg_match('/^(?: ?(?<!^ )[a-z][a-z\d]*)+$/i', $test)) {
    echo 'is a string of one or more space-delimited alphanumeric words (each starting with a letter)';
} else {
    echo 'validation failed';
}
    

Upvotes: 0

Dan McGrath
Dan McGrath

Reputation: 42046

Does a regex like this help?

^[a-zA-Z0-9]\w*$

It means:

  • ^ = this pattern must start from the beginning of the string
  • [a-zA-Z0-9] = this char can be any letter (a-z and A-Z) or digit (0-9, also see \d)
  • \w = A word character. This includes letters, numbers and white-space (not new-lines by default)
  • * = Repeat thing 0 or more times
  • $ = this pattern must finish at the end of the string

To satisfy the condition I missed, try this

^[a-zA-Z0-9]*\w*[a-zA-Z]+\w*$

The extra stuff I added lets it have a digit for the first character, but it must always contain a letter because of the [a-zA-Z]+ since + means 1 or more.

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 817228

If this is homework, you maybe should just learn regular expressions:

Upvotes: 1

YOU
YOU

Reputation: 123937

Try

'/^[a-zA-Z][\w ]+$/'

Upvotes: 0

Related Questions