I want to create regex which will accept combination of alphabets, special characters,numbers but not only alphabets or special characters or numbers
For example : It should accept
- 1 Slice brown bread (wheat)
- 1 Tbsp
- 1/2 cup
But it should not accept
- Slice brown bread
- 1
- @#%&%&*
This is what I have tried:
regex:/^(?![0-9]*$)[a-zA-Z0-9s-()/ ]+$/'
This regex allow user to accept combination of alphabets, numbers and special characters but not only numbers.
Advertisement
Answer
By chaining a few negative lookaheads to the regex, so it won’t match when there’s only 1 of the types + whitespaces on the same line.
$str = '1 Slice brown bread (wheat) 1 Tbsp 1/2 cup Slice brown bread 1 @#%&%&*'; $re = '/^(?!W+$)(?![ds]+$)(?![A-Za-zs]+$).+$/m'; preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0); var_dump($matches);
Btw, in the examples, all the acceptables seem to start with a digit, and have letters.
So with $re = '/^(?=.*[A-Za-z])d+.+$/m';
, to match lines that start with a number and have at least a letter, it would also only match the first 3 examples.