Reputation: 1335
I want to use preg_match()
such that there should not be special characters such as @#$%^&/ '
in a given string.
For example :
Coding
: Outputs valid
: Outputs Invalid (string beginning with space)Project management
: Outputs valid (space between two words are valid)Design23
: Outputs valid23Designing
: Outputs invalid123
:Outputs invalidI tried but could not reach to a valid answer.
Upvotes: 5
Views: 360
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
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 stringTo 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
Reputation: 817228
If this is homework, you maybe should just learn regular expressions:
Upvotes: 1