1

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:

  1. if the string contains multiple words it should be separated by space only not other symbols(/_) .

  2. Both caps and small letters are allowed .

Valid scenarios:

  1. Ready to dispatch
  2. ReaDy To Dispatch
  3. cancelled
  4. CanceLled

Invalid scenarios:

  1. Ready_to_dispatch

  2. Ready-to-Dispatch

    $pattern=[a-zA-Z];
    $validation=preg_match($pattern,$request->status);
    if($validation){
      //My logic executes if it matches the pattern
    }
    
user3783243
  • 5,368
  • 5
  • 22
  • 41
  • 1
    See [Regular expression to allow spaces between words](https://stackoverflow.com/q/15472764/3832970) – Wiktor Stribiżew Nov 21 '21 at 12:21
  • Does this answer your question? [Regular expression to allow spaces between words](https://stackoverflow.com/questions/15472764/regular-expression-to-allow-spaces-between-words) – Ryszard Czech Nov 21 '21 at 21:40

2 Answers2

1

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
}
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

You can update your $pattern = "^[a-zA-Z0-9_ ]*$" or just add a space only. $pattern add under quota:

$pattern="^[a-zA-Z0-9_ ]*$";
$validation=preg_match($pattern,$request->status);
if($validation){
  //My logic executes if it matches the pattern
}
Md Atiqur
  • 456
  • 6
  • 10