How can I check if a PHP string contains any white space? I want to check if white space is in there, and then echo back an error message if true
if(strlen($username) == whitespace ){
echo "<center>Your username must not contain any whitespace</center>";
if ( preg_match('/\s/',$username) ) ....
This solution is for the inverse problem: to know if a string contains at least one word.
/**
* Check if a string contains at least one word.
*
* #param string $input_string
* #return boolean
* true if there is at least one word, false otherwise.
*/
function contains_at_least_one_word($input_string) {
foreach (explode(' ', $input_string) as $word) {
if (!empty($word)) {
return true;
}
}
return false;
}
If the function return false there are no words in the $input_string.
So, you can do something like that:
if (!contains_at_least_one_word($my_string)) {
echo $my_string . " doesn't contain any words.";
}
Try this method:
if(strlen(trim($username)) == strlen($username)) {
// some white spaces are there.
}
Try this too :
if (count(explode(' ', $username)) > 1) {
// some white spaces are there.
}
Try this:
if ( preg_match('/\s/',$string) ){
echo "yes $string contain whitespace";
} else {
echo "$string clear no whitespace ";
}
Other Method :
$string = "This string have whitespace";
if( $string !== str_replace(' ','',$string) ){
//Have whitespace
}else{
//dont have whitespace
}
I've found another good function which is working fine for searching some charsets in a string - strpbrk
if (strpbrk($string, ' ') !== false) {
echo "Contain space";
} else {
echo "Doesn't contain space";
}
PHP provides a built-in function ctype_space( string $text ) to check for whitespace characters. However, ctype_space() checks if every character of the string creates a whitespace. In your case, you could make a function similar to the following to check if a string has whitespace characters.
/**
* Checks string for whitespace characters.
*
* #param string $text
* The string to test.
* #return bool
* TRUE if any character creates some sort of whitespace; otherwise, FALSE.
*/
function hasWhitespace( $text )
{
for ( $idx = 0; $idx < strlen( $text ); $idx += 1 )
if ( ctype_space( $text[ $idx ] ) )
return TRUE;
return FALSE;
}
Related
Am using code below to check presence of certain character via php and it works fine.
with code below, I can check if character a is presence in the variable and is working.
$mystring = 'my food is okay. its delicious';
$findme = 'a';
$pos = strpos($mystring, $findme);
if ($pos !== false) {
echo 'data found';
}
Here is my issue: I need to check the also presence of multiple characters like m,e,s etc. any idea on how to achieve that.
There are many ways to do this, from using multiple strpos to comparisons after a str_replace. Here we can split the string into an array and calculate the intersection with another array:
$mystring = 'my food is okay. its delicious';
$findme = ['m', 'e', 's'];
Check for ANY of the characters in the array:
if(array_intersect($findme, str_split($mystring))) {
echo "1 or more found";
}
Check for ALL of the characters in the array:
if(array_intersect($findme, str_split($mystring)) == $findme) {
echo "all found";
}
And for fun, run the array through a callback and filter it based upon whether it is in the string. This will check for ANY:
if(array_filter($findme, function($v) use($mystring) {
return strpos($mystring, $v) !== false;
}))
{
echo "1 or more found";
}
This will check for ALL:
if(array_filter($findme, function($v) use($mystring) {
return strpos($mystring, $v) !== false;
}) == $findme)
{
echo "all found";
}
Another way to do this is with trim.
$mystring = 'my food is okay. its delicious';
$findme = 'ames';
$any = trim($findme, $mystring) != $findme;
$all = !trim($findme, $mystring);
This function will do the trick for you:
/**
* Takes an array of needles and searches a given string to return all
* needles found in the string. The needles can be words, characters,
* numbers etc.
*
* #param array $needles
* #param string $haystack
* #return array|null
*/
function searchString(array $needles, string $haystack): ?array
{
$itemsFound = [];
foreach($needles as $needle) {
if (strpos($haystack, $needle) !== false) {
$itemsFound[] = $needle;
}
}
return $itemsFound;
}
https://3v4l.org/5oXGp
I need to check in a string of digits, ie all other characters such as ~; & * ^ # & ^ Should not fall under check. I need it to form validation. Now i use that construction:
return ( ! preg_match("/^([0-9])+$/i", $str)) ? FALSE : TRUE;
I have a form for edeiting firstname and lastname of users. Also when someone try to add name with characters somth like that: "kickman!##$%^&())))(&^%$##$%" my form should complete validation without errors. But if i have there any digit i should get an error, somth like : "123kickman!##$%^&())))(&^%$##$%".
Try this:
if (!preg_match("#^[a-zA-Z0-9]+$#", $text)){
echo 'String also contains other characters.';
} else {
echo 'String only contains numbers and letters.';
}
or this:
function countDigits($str)
{
return preg_match_all( "/[0-9]/", $str );
}
If you are trying to see if all characters are digits, just create a function and pass the string to it:
$x = match("01234");
echo $x."<br>";
$x = match("0$#21234");
echo $x."<br>";
function match($str)
{
return ( ! preg_match("/^([0-9])+$/i", $str)) ? 0 : 1;
}
How about:
Edit according to question update:
if (preg_match('/\d/', $string)) {
echo "KO, at least one digit\n";
} else {
echo "OK, no digits found\n";
}
Or, in a function:
return !preg_match('/d/', $string);
I am trying to make a word filter in php, and I have come across a previous Stackoverlow post that mentions the following to check to see if a string contains certain words. What I want to do is adapt this so that it checks for various different words in one go, without having to repeat the code over and over.
$a = 'How are you ?';
if (strpos($a,'are') !== false) {
echo 'true';
}
Will it work if I mod the code to the following ?......
$a = 'How are you ?';
if (strpos($a,'are' OR $a,'you' OR $a,'How') !== false) {
echo 'true';
}
What is the correct way of adding more than one word to check for ?.
To extend your current code you could use an array of target words to search for, and use a loop:
$a = 'How are you ?';
$targets = array('How', 'are');
foreach($targets as $t)
{
if (strpos($a,$t) !== false) {
echo 'one of the targets was found';
break;
}
}
Keep in mind that the use of strpos() in this way means that partial word matches can be found. For example if the target was ample in the string here is an example then a match will be found even though by definition the word ample isn't present.
For a whole word match, there is an example in the preg_match() documentation that can be expanded by adding a loop for multiple targets:
foreach($targets as $t)
{
if (preg_match("/\b" . $t . "\b/i", $a)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
}
Read it somewhere:
if(preg_match('[word1|word2]', $a)) { }
if (strpos($ro1['title'], $search)!==false or strpos($ro1['description'], $search)!== false or strpos($udetails['user_username'], $search)!== false)
{
//excute ur code
}
If you have a fixed number of words, which is not too big you can easily make it like this:
$a = 'How are you ?';
if (strpos($a,'are') !== false || strpos($a,'you') !== false || strpos($a,'How') !== false) {
echo 'true';
}
I built methods using both str_contains and preg_match to compare speeds.
public static function containsMulti(?string $haystackStr, array $needlesArr): bool
{
if ($haystackStr && $needlesArr) {
foreach ($needlesArr as $needleStr) {
if (str_contains($haystackStr, $needleStr)) {
return true;
}
}
}
return false;
}
preg_match is always a lot slower (2-10 times slower, depending on several factors), but could be useful if you want to extend it for whole-word matching, etc.
public static function containsMulti(?string $haystackStr, array $needlesArr): bool
{
if ($haystackStr && $needlesArr) {
$needlesRegexStr = implode('|', array_map('preg_quote', $needlesArr));
return (bool) preg_match('/(' . $needlesRegexStr . ')/', $haystackStr);
}
return false;
}
If you need a multibyte-save version. try this
/**
* Determine if a given string contains a given substring.
*
* #param string $haystack
* #param string|string[] $needles
* #param bool $ignoreCase
* #return bool
*/
public static function contains($haystack, $needles, $ignoreCase = false)
{
if($ignoreCase){
$haystack= mb_strtolower($haystack);
$needles = array_map('mb_strtolower',$needles);
}
foreach ((array) $needles as $needle) {
if ($needle !== '' && mb_strpos($haystack, $needle) !== false) {
return true;
}
}
return false;
}
I want an if statement that uses same thingy like mysql something LIKE '%something%'
I want to build an if statement in php.
if ($something is like %$somethingother%)
Is it possible?
The reason for me asking this question is that I don't want to change the MySQL command, it's a long page with many stuff on it, I don't want to build a different function for this.
Let me know if this is possible, if possible then how to do it .
if ($something is like %$somethingother%)
Is it possible?
no.
I don't want to change the MySQL command, it's a long page with many stuff on it
Use some good editor, that supports regular expressions in find & replace, and turn it to something like:
if(stripos($something, $somethingother) !== FALSE){
}
I know, this question isn't actual but I've solved similar problem :)
My solution:
/**
* SQL Like operator in PHP.
* Returns TRUE if match else FALSE.
* #param string $pattern
* #param string $subject
* #return bool
*/
function like_match($pattern, $subject)
{
$pattern = str_replace('%', '.*', preg_quote($pattern, '/'));
return (bool) preg_match("/^{$pattern}$/i", $subject);
}
Examples:
like_match('%uc%','Lucy'); //TRUE
like_match('%cy', 'Lucy'); //TRUE
like_match('lu%', 'Lucy'); //TRUE
like_match('%lu', 'Lucy'); //FALSE
like_match('cy%', 'Lucy'); //FALSE
look on strstr function
Use this function which works same like SQL LIKE operator but it will return boolean value and you can make your own condition with one more if statement
function like($str, $searchTerm) {
$searchTerm = strtolower($searchTerm);
$str = strtolower($str);
$pos = strpos($str, $searchTerm);
if ($pos === false)
return false;
else
return true;
}
$found = like('Apple', 'app'); //returns true
$notFound = like('Apple', 'lep'); //returns false
if($found){
// This will execute only when the text is like the desired string
}
Use function, that search string in another string like: strstr, strpos, substr_count.
strpos() is not working for so i have to use this preg_match()
$a = 'How are you?';
if (preg_match('/\bare\b/', $a)) {
echo 'true';
}
like in this e.g i am matching with word "are"
hope for someone it will be helpful
But you will have to give lowercase string then it will work fine.
Example of strstr function:
$myString = "Hello, world!";
echo strstr( $myString, "wor" ); // Displays 'world!'
echo ( strstr( $myString, "xyz" ) ? "Yes" : "No" ); // Displays 'No'
If you have access to a MySQL server, send a query like this with MySQLi:
$SQL="select case when '$Value' like '$Pattern' then 'True' else 'False' end as Result";
$Result=$MySQLi->query($SQL)->fetch_all(MYSQLI_ASSOC)[0]['Result'];
Result will be a string containing True or False. Let PHP do what it's good for and use SQL for likes.
I came across this requirement recently and came up with this:
/**
* Removes the diacritical marks from a string.
*
* Diacritical marks: {#link https://unicode-table.com/blocks/combining-diacritical-marks/}
*
* #param string $string The string from which to strip the diacritical marks.
* #return string Stripped string.
*/
function stripDiacriticalMarks(string $string): string
{
return preg_replace('/[\x{0300}-\x{036f}]/u', '', \Normalizer::normalize($string , \Normalizer::FORM_KD));
}
/**
* Checks if the string $haystack is like $needle, $needle can contain '%' and '_'
* characters which will behave as if used in a SQL LIKE condition. Character escaping
* is supported with '\'.
*
* #param string $haystack The string to check if it is like $needle.
* #param string $needle The string used to check if $haystack is like it.
* #param bool $ai Whether to check likeness in an accent-insensitive manner.
* #param bool $ci Whether to check likeness in a case-insensitive manner.
* #return bool True if $haystack is like $needle, otherwise, false.
*/
function like(string $haystack, string $needle, bool $ai = true, bool $ci = true): bool
{
if ($ai) {
$haystack = stripDiacriticalMarks($haystack);
$needle = stripDiacriticalMarks($needle);
}
$needle = preg_quote($needle, '/');
$tokens = [];
$needleLength = strlen($needle);
for ($i = 0; $i < $needleLength;) {
if ($needle[$i] === '\\') {
$i += 2;
if ($i < $needleLength) {
if ($needle[$i] === '\\') {
$tokens[] = '\\\\';
$i += 2;
} else {
$tokens[] = $needle[$i];
++$i;
}
} else {
$tokens[] = '\\\\';
}
} else {
switch ($needle[$i]) {
case '_':
$tokens[] = '.';
break;
case '%':
$tokens[] = '.*';
break;
default:
$tokens[] = $needle[$i];
break;
}
++$i;
}
}
return preg_match('/^' . implode($tokens) . '$/u' . ($ci ? 'i' : ''), $haystack) === 1;
}
/**
* Escapes a string in a way that `UString::like` will match it as-is, thus '%' and '_'
* would match a literal '%' and '_' respectively (and not behave as in a SQL LIKE
* condition).
*
* #param string $str The string to escape.
* #return string The escaped string.
*/
function escapeLike(string $str): string
{
return strtr($str, ['\\' => '\\\\', '%' => '\%', '_' => '\_']);
}
The code above is unicode aware to be able to catch cases like:
like('Hello 🙃', 'Hello _'); // true
like('Hello 🙃', '_e%o__'); // true
like('asdfas \\🙃H\\\\%🙃É\\l\\_🙃\\l\\o asdfasf', '%' . escapeLike('\\🙃h\\\\%🙃e\\l\\_🙃\\l\\o') . '%'); // true
You can try all of this on https://3v4l.org/O9LX0
I think it's worth mentioning the str_contains() function available in PHP 8 which performs a case-sensitive check indicating whether a string is contained within another string, returning true or false.
Example taken from the documentation:
$string = 'The lazy fox jumped over the fence';
if (str_contains($string, 'lazy')) {
echo "The string 'lazy' was found in the string\n";
}
if (str_contains($string, 'Lazy')) {
echo 'The string "Lazy" was found in the string';
} else {
echo '"Lazy" was not found because the case does not match';
}
//The above will output:
//The string 'lazy' was found in the string
//"Lazy" was not found because the case does not match
See the full documentation here.
like_match() example is the best
this one witch SQL reqest is simple (I used it before), but works slowly then like_match() and exost database server resources when you iterate by array keys and every round hit db server with request usually not necessery. I made it faster ferst cutting / shrink array by pattern elements but regexp on array works always faster.
I like like_match() :)
I am working on writing a PHP login system. I have everything that I need working, but I would like to verify that a username entered during the registration only contains alphanumeric characters. So how could I take a variable, say $username, and ensure that it contained only alphanumeric characters?
if(preg_match('/^\w{5,}$/', $username)) { // \w equals "[0-9A-Za-z_]"
// valid username, alphanumeric & longer than or equals 5 chars
}
OR
if(preg_match('/^[a-zA-Z0-9]{5,}$/', $username)) { // for english chars + numbers only
// valid username, alphanumeric & longer than or equals 5 chars
}
The Best way I recommend is this :-
$str = "";
function validate_username($str)
{
$allowed = array(".", "-", "_"); // you can add here more value, you want to allow.
if(ctype_alnum(str_replace($allowed, '', $str ))) {
return $str;
} else {
$str = "Invalid Username";
return $str;
}
}
If you don't care about the length, you can use:
if (ctype_alnum($username)) {
// Username is valid
}
http://www.php.net/manual/en/function.ctype-alnum.php
try this
function filterName ($name, $filter = "[^a-zA-Z0-9\-\_\.]"){
return preg_match("~" . $filter . "~iU", $name) ? false : true;
}
if ( !filterName ($name) ){
print "Not a valid name";
}
A little bit late but I am using the following function to test usernames or other types of alphanum-like strings. It tests alphanum chars only by default but you can add more characters such as . (dot), - (dash) or _ (underscore) to the whitelist.
It will also prevent consecutive chars for the chars specified as $more_chars.
function valid_alphanum_string($str, $more_chars = '') {
# check type
if (!is_string($str)) return false;
# handle allowed chars
if (mb_strlen($more_chars) > 0) {
# don't allow ^, ] and \ in allowed chars
$more_chars = str_replace(array('^', ']', '\\'), '', $more_chars);
# escape dash
$escaped_chars = strpos($more_chars, '-') !== false
? str_replace('-', '\-', $more_chars)
: $more_chars;
# allowed chars must be non-consecutive
for ($i=0; $i < mb_strlen($more_chars); $i++) {
$consecutive_test = preg_match('/[' . $more_chars[$i] . '][' . $escaped_chars . ']/', $str);
if ($consecutive_test === 1) return false;
}
# allowed chars shouldn't be at the start and the end of the string
if (strpos($more_chars, $str[0]) !== false) return false;
if (strpos($more_chars, $str[mb_strlen($str) - 1])) return false;
}
else $escaped_chars = $more_chars;
$result = preg_match('/^[a-zA-Z0-9' . $escaped_chars . ']{4,}$/', $str);
return $result === 1 ? true : false;
}
If you are allowing the basic alpha-numeric username, You can check alphanumeric value with a predefined template like this:
preg_match([[:alnum:]],$username)&&!preg_match([[:space:]],$username)
The second part returns false if the string contains any spaces.