0

I am trying to write a regex that will only allow text uppercase and lower. I had no idea how to write any regex so I found a post on Stack

How do I write a regex in PHP to remove special characters?

With a link to a place to learn. The tut is fantastic so do read if yuo have trouble with regex.

if( preg_match('/^([A-Za-z\s]+)&/', $pagename) ) {
 //do stuff
 } 
 else  
 {echo"no special char or num";}

How ever it fails. If I type for example

New Web Page

it should allow this but it fails.

2
  • fyi \s matches for a "whitespace" character (eg: a space, tab, etc.). If you really want to only match letters, you need to remove that. Also, you can shorten the regex by using the i modifier. Commented Jan 28, 2013 at 16:20
  • are you sure the $pagename contains the correct value that you are parsing? Commented Jan 28, 2013 at 16:22

3 Answers 3

1

$ is the right sign for ends with not &

it should be /^([A-Za-z\s]+)$/

Sign up to request clarification or add additional context in comments.

Comments

1

I am trying to write a regex that will only allow text uppercase and lower. All you need is

 '/^([A-Z]+)$/i'
            ^
            |-------- Note used $ instead of &

Comments

0

You don't need the round brackets, and replace & with $ (end of string).

5 Comments

He needs the brackets to show that a-z and A-Z are character sets
I suspect he means the parentheses rather than the brackets - technically the parentheses are unnecessary unless you want to create/store a sub-pattern.
(), [], {} - are these A) (round) brackets, square brackets, curly brackets, or B) parens, brackets, braces? :-)
OP's looking for a true or false, so he needs the square brackets but not the round ones so /^[a-zA-Z\s]+$/ would do exactly what he wants.
Yes, brackets means (), should've been clearer I meant those and not the Square brackets []!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.