How to check if more than one space or beginning has space in PHP

Viewed 263
  1. Hello World
  2. Hello World
  3. hello world

    or if the very beginning has space
  4. Hello World

It works if $q has normal values but I am getting $q value from search input and so it does not work except case 1.

$q = Input::get('q');

if(preg_match("/^\s+/", $q) || preg_match("/\s{2,}/", $q)) {
        echo 'Found Spaces';    
}
5 Answers

Instead of Input::get('q'); use $q = $_GET['q'];
So your code becomes:

   $q = $_GET['q'];
    
    if(preg_match("/^\s+/", $q) || preg_match("/\s{2,}/", $q)) {
            echo 'Found Spaces';    
    }
if(preg_match("/^\s+/", $q) || preg_match("/\s{2,}/", $q))
    {
       
    }
 
/\s+/g
  • \s to match space.
  • + to said at least one.
  • g globally tag, all matches.

You can use a single call to preg_match with an alternation | to check for both scenario's.

As \s can also match a newline, you can use \h to match a horizontal whitespace char.

^\h|\h\h

Regex demo

$q = Input::get('q');

if(preg_match("/^\h|\h\h/", $q) ) {
    echo 'Found Spaces';
}

Have you tried using PHP trim() function? Use trim() to remove redundant whitespaces, then apply more advanced filter or whatever you name it. In case you want a boolean value, just check if the original string is different from trimmed string. Document: https://www.php.net/manual/en/function.trim.php

Related