Reputation: 652
Hello World
Hello World
hello world
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
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
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
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
Reputation: 1144
/\s+/g
\s
to match space.+
to said at least one.g
globally tag, all matches.Upvotes: 1