Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Regex for exact match

Tags:

regex

php

Here is the regex I currently have (which kind of works):

$regex = '/[\w ]{7,30}/';

My revision looks like what I want, but it does not work at all:

$regex = '^[\w ]{7,30}$';

Here is how I am using the regex:

public function isValid( $value )
{

    $regex = '/^[\w ]{7,30}$/';
    return preg_match( $regex, $value ) ? true : false;

}

I am trying to match the following:

  • Any lower/upper case letter
  • Any digit
  • Can contain spaces
  • Cannot contain line breaks or tab space
  • Minimum of 7 characters
  • Maximum of 30 characters

Valid inputs:

  • Testing
  • Test ing
  • Test123
  • Test 123
  • Test___

Invalid inputs:

  • Testing#
  • Testin8+
  • Tester1&

The first regex will match all valid inputs, as well as invalid (as long as the first four characters are valid, it doesn't care about the rest). The second regex matches nothing.

like image 779
Nahydrin Avatar asked Dec 03 '25 02:12

Nahydrin


1 Answers

Try combining both like so:

$regex = '/^[\w ]{7,30}$/';
like image 127
Drew Galbraith Avatar answered Dec 05 '25 14:12

Drew Galbraith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!