John Davidson

php - How to write a regex pattern which accepts space in between words?

0 comments
Message:


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
    }




My Answer:
To write a regex pattern that accepts space in between words, you can use the following pattern:

php
$pattern = '/^[a-zA-Z ]+$/';


Explanation of the pattern:
- `^` asserts the start of the string
- `[a-zA-Z ]` matches any uppercase or lowercase letter or a space
- `+` specifies that the previous character (letter or space) can occur one or more times
- `$` asserts the end of the string

You can use this pattern in your code as follows:

php
$pattern = '/^[a-zA-Z ]+$/';
$validation = preg_match($pattern, $request->status);
if ($validation) {
// Your logic executes if it matches the pattern
}


This pattern will only allow strings that consist of letters (both uppercase and lowercase) and spaces. It will not allow other symbols like `/` or `_`.

Rate this post

3 of 5 based on 6246 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us