tags:

views:

75

answers:

3
+4  Q: 

preg_match in php

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 valid
23Designing : outputs invalid
123 :Outputs invalid

I tried but could not reach to a valid answer.

+1  A: 

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.

Dan McGrath
Ah, just seen the 123 invalid. This smells like homework...
Dan McGrath
Of course, there is probably a better way to do this and the standard "I have not tested this" disclaimer applies
Dan McGrath
A: 

Try

'/^[a-zA-Z][\w ]+$/'
S.Mark
Thanks i got the result and the logic too
Satish
A: 

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

Felix Kling
Thanks for references....i got it now
Satish