I am very new to the regex patterns. I am developing one api which accepts the user value(status), based on the status it will perform the filtering operation upto this it’s working fine.
Now what my requirement is I want to accept the value based on:
-
if the string contains multiple words it should be separated by
spaceonly not other symbols(/_) . -
Both caps and small letters are allowed .
Valid scenarios:
- Ready to dispatch
- ReaDy To Dispatch
- cancelled
- CanceLled
Invalid scenarios:
-
Ready_to_dispatch
-
Ready-to-Dispatch
$pattern=[a-zA-Z]; $validation=preg_match($pattern,$request->status); if($validation){ //My logic executes if it matches the pattern }
>Solution :
For the pattern you could repeat the character class one or more times, and as only a space is allowed between the words, optionally repeat the same character class preceded by a space.
^[A-Za-z]+(?: [A-Za-z]+)*$
You could update the code to placing the pattern between quotes and add delimiters / around the pattern.
$pattern="/^[A-Za-z]+(?: [A-Za-z]+)*$/";
$validation = preg_match($pattern,$request->status);
if($validation){
//My logic executes if it matches the pattern
}