Regular expression in PHP, with range of characters, but that excludes specific ones

✔ Recommended Answer

You can use:



  • ^(?=.*[\/.@]) - checks that after beginning of string(^) somewhere there is any of symbols: /,.,@,
  • [^=*_xyz]{10,} - checks that your line at least 10 symbols and doesn't contain any of *,_,x,y,z,
  • $ - marker of the end of the string, so that no forbidden symbols could be matched after first 10 "good" ones.


Answered By: markalex

Method #2

To create a regular expression in PHP that includes a range of characters but excludes specific ones, you can use a negative character set. Here's an example:

Let's say you want to match any string that contains letters between "a" and "z", but excludes the letters "q" and "x". You can create a regular expression like this:

$regex = '/^[a-pr-wyz]+$/i';

Here's how this regular expression works:

  • ^ matches the start of the string
  • [a-pr-wyz] matches any letter between "a" and "z", except for "q" and "x". The range a-pr matches all letters from "a" to "p", while r-wyz matches all letters from "r" to "z".
  • + means that the previous character set can appear one or more times.
  • $ matches the end of the string.
  • /i at the end of the regular expression means the pattern is case-insensitive.

With this regular expression, the following strings would match:

  • "abc"
  • "hello"
  • "xylophone"
  • "zoo"
  • "pqr"
  • "wxyz"

And the following strings would not match:

  • "Qwerty"
  • "123"
  • "aaabbb"
  • "this is a sentence"
  • "quick brown fox"
  • "zero"

Note that this regular expression only matches strings that consist entirely of letters between "a" and "z", excluding "q" and "x". If you want to allow other characters in the string, you'll need to modify the regular expression accordingly.


Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755