Anonymous Girl
Anonymous Girl

Reputation: 652

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

  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';    
}

Upvotes: 3

Views: 1010

Answers (5)

The fourth bird
The fourth bird

Reputation: 163632

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';
}

Upvotes: 1

Amir Ahmed
Amir Ahmed

Reputation: 119

if(preg_match("/^\s+/", $q) || preg_match("/\s{2,}/", $q))
    {
       
    }
 

Upvotes: 2

Amit
Amit

Reputation: 120

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';    
    }

Upvotes: 3

Huy Phạm
Huy Phạm

Reputation: 1023

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

Upvotes: 0

Juan Eizmendi
Juan Eizmendi

Reputation: 1144

/\s+/g
  • \s to match space.
  • + to said at least one.
  • g globally tag, all matches.

Upvotes: 1

Related Questions