How to check if " " exist? - php

When I print a variable, I get a blank result and when I inspect the element I see that .
I tried to check if the variables is empty or equals this value:
ir( empty($string) || $string == " " || strpos($string, " ") || $string == " "){
//Do Something.
}
But the code inside that condition is not executed.
When I var_dump($string), I get:
string(2) " "
What should I do to check if the variable equals or contain that?

The solution, If the utf-8 is used:
$a = str_replace("\xC2\xA0", '', $a);
If ASCII :
$a = str_replace("\xA0", '', $a);
Then the $a is empty now and you could check it using if(empty($a))
The answer exists here: Does html_entity_decode replaces also? If not how to replace it?

First of all, People get tripped up on this move all the time...
strpos($string, " ")
If is at the start of your string, then the evaluated result is 0 ("offset position") AND 0 is loosely compared to false in the way that you have crafted your conditional expression.
You need to explicitly check for false (strict check) from strpos() like this:
if (empty($string) || strpos($string, " ") !== false || $string == " ") {
//Do Something.
}
However, that is NOT your actual issue because...
You have a multibyte space evidenced by when you "highlight" the character with your cursor -- it only has a character length of one, but when you call var_dump() there is a byte count of 2.
trim() can't help you. ctype_space() can't help you. You need something that is multibyte aware.
To allow the most inclusive match, I'll employ a regular expression that will search for all whitespace characters, invisible control characters, and unused code points.
if (empty($string) || preg_match("/^[\pZ\pC]+$/u", $string)) {
This will check if the string is truly empty or is entirely composed of one or more of the aforementioned characters.
Here's a little demo: https://3v4l.org/u7eoK
(I don't really think this is a issue, so I am leaving that out of my solution.)
Scroll down this resource: https://www.regular-expressions.info/unicode.html

Related

php trim() not working to remove empty blank spaces

I have a situation where i have to ignore empty data when processing the set of string. Some of the string are valid and some comes with just white spaces (created using spacebar in keyboard)
for example the data would come like this in the program...
$x = " ";
In this case i have to tell this $x is empty though there are two white spaces in it.
I tried using PHP empty() function but it returns false. i tried PHP trim() function but it does not help to remove this empty white spaces for the variable to become empty.
How can i get this validated as empty in PHP ?
trim() removes all the whitespaces from the beginning and end of a string and returns the trimmed string
So you'll need to feed the returned string of trim() to empty():
<?php
$x = " ";
var_dump(empty($x)); // false
var_dump(trim($x)); // string(0) ""
var_dump(empty(trim($x))); // true
Try it online!
You can also write a custom function for check possible multiple white-spaces.
$str = " ";
function isOnlyWhitespace($str) {
return strlen($str) === substr_count($str, ' ') ? true : false;
}
echo isOnlyWhitespace($str); // 1

PHP - Check for leading 0's in 2 comma-delimited integers

I have a user-input string with 2 comma-delimited integers.
Example (OK):
3,5
I want to reject any user input that contains leading 0's for either number.
Examples (Bad):
03,5
00005,3
05,003
Now what I could do is separate the two numbers into 2 separate string's and use ltrim on each one, then see if they have changed from before ltrim was executed:
$string = "03,5";
$string_arr = explode(",",$string);
$string_orig1 = $string_arr[0];
$string_orig2 = $string_arr[1];
$string_mod1 = ltrim($string_orig1, '0');
$string_mod2 = ltrim($string_orig2, '0');
if (($string_mod1 !== $string_orig1) || ($string_mod2 !== $string_orig2)){
// One of them had leading zeros!
}
..but this seems unnecessarily verbose. Is there a cleaner way to do this? Perhaps with preg_match?
You could shorten the code and check if the first character of each part is a zero:
$string = "03,5";
$string_arr = explode(",",$string);
if ($string_arr[0][0] === "0" || $string_arr[1][0] === "0") {
echo "not valid";
} else {
echo "valid";
}
Here is one approach using preg_match. We can try matching for the pattern:
\b0\d+
The \b would match either the start of the string, or a preceding comma separator.
If we find such a match, it means that we found one or more numbers in the CSV list (or a single number, if only one number present) which had a leading zero.
$input = "00005,3";
if (preg_match("/\b0\d+/", $input)) {
echo "no match";
}
You can do a simple check that if the first character is 0 (using [0]) or that ,0 exists in the string
if ( $string[0] == "0" || strpos($string, ",0") !== false ) {
// One of them had leading zeros!
}
All the current answers fail if any of the values are simply 0.
You can just convert to integer and back and compare the result.
$arr = explode(',', $input);
foreach($arr as $item) {
if( (str)intval($item) !== $item ) {
oh_noes();
}
}
However I am more curious as to why this check matters at all.
One way would be with /^([1-9]+),(\d+)/; a regex that checks the string starts with one or more non-zero digits, followed by a comma, then one or more digits.
preg_match('/^([1-9]+),(\d+)/', $input_line, $output_array);
This separates the digits into two groups and explicitly avoids leading zeros.
This can be seen on Regex101 here and PHPLiveRegex here.

Why strpos + strlen is not secure in PHP (ex: exact matching)

I had a discussion with my teacher about the mb_ functions. Whatever, one thing leading to another, we changed the subject and he gave me an example where strpos and strlen could be problematic, according to him:
$input = "something"; # input given by the user
$string = "hello"; # string to match
if ( strpos($input, $string) !== false && strlen($input) < strlen($string) ) {
echo "Correct input";
} else {
echo "Incorrect input";
}
(The question is not about how to match 2 strings)
According to my teacher, there may be a way to validate the statement and execute the code echo "Correct input";.
However, I can't see a flaw in this. Maybe there could be a problem with encoding? Do you have any idea?
okey i think that the flaw will be the if statement logic
how will you use strpos function which check the position of the first occurrence of a substring in a string , and in the same time you want to check if the input is greater than the subject ?
by logic it is impossible

How to disable ' - ; : ~ ` from input and remove from string?

I tried to add extra security by removing special characters. I want to allow letters, numbers and ? = & only.
I tried:
if (strpos($_SERVER['REQUEST_URI'],'\'')) { echo 'true'; }
I cannot just simply put ' in between the '' as it breaks it so I tried adding the \ but it didn't work.
Is there a way to detect all the symbols in the url string or input field?
EDIT:
tried adding < simply into the list
if (preg_match('#[#*,!$\'\-;:<>~`^|\(\\)\\{\\}\\[\\]]#i', $_SERVER['REQUEST_URI']) || strpos($_SERVER['REQUEST_URI'],'script')) {
echo 'Cannot do that';
}
I tried adding ([\<])([^\>]{1,})*([\>]) into there but it didn't work.
I also tried adding a condition if strcmp($_SERVER['REQUEST_URI'], strip_tags($_SERVER['REQUEST_URI'])) != 0
and when i added into the url, it didn't do anything
Use preg_match to test for anything but the characters you want:
if (preg_match('#[^a-z0-9?=&]#i', $str)) { echo 'true'; }
Use preg_replace to remove them:
$str = preg_replace('#[^a-z0-9?=&]#i', '', $str);
If you just want to prohibit certain characters, use a regular expression that just matches those characters:
if (preg_match('#[\'\-;:~`]#i', $str)) { echo 'true'; }
You can fix that using double quotes as strings delimiter, try this
if (strpos($_SERVER['REQUEST_URI'],"'")) { echo 'true'; }
One thing that none of the posts addressed is why strpos didn't work for you. strpos can return two types. It can return an integer that is greater than or equal to zero. 0 being the first character. It can also return a boolean type false. To check if if strpos found a match it would have to have been written like this:
if (strpos($_SERVER['REQUEST_URI'],'\'') !== false) { echo 'true'; }
From the PHP Documentation The comparison $a !== $b operator works this way:
return TRUE if $a is not equal to $b, or they are not of the same type.
Information on strpos returning two types (boolean false or an integer) can be found in this PHP strpos Documentation. In particular:
Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
So as you can see 0 and false are not the same thing which is why your test failed.
As for security and strings in PHP I recommend you look at this StackOverflow article for some opinions on the matter.

Checking to see if a string contains any characters

I would like to check and see if a given string contains any characters or if it is just all white space. How can I do this?
I have tried:
$search_term= " ";
if (preg_match('/ /',$search_term)) {
// do this
}
But this affects search terms like this as well:
$search_term= "Mark Zuckerburg";
I only want a condition that checks for all white space and with no characters.
Thanks!
ctype_space does this.
$search_term = " ";
if (ctype_space($search_term)) {
// do this
}
The reason your regular expression doesn’t work is that it’s not anchored anywhere, so it searches everywhere. The right regular expression would probably be ^\s+$.
The difference between ctype_space and trim is that ctype_space returns false for an empty string. Use whatever’s appropriate. (Or ctype_space($search_term) || $search_term === ''…)
Use trim():
if(trim($search_term) == ''){
//empty or white space only string
echo 'Search term is empty';
}
trim() will cut whitespace from both start and end of a string - so if the string contains only whitespace trimming it will return empty string.

Categories