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
Related
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
I'm building a form that'll create a Word doc. There's a part where the user will create a list, and will separete the list lines by using the " | " (vertical bar) as a delimeter. I'm trying to explode() a string like this: "First line| Second line| Third and last line |". As you guys saw, I placed a vertival bar delimiter after the last line, that's 'cause the user will probably do this mistake, and it will generate a empty line on the list.
I'm trying to avoid this error by using something like this:
$lines = explode("|",$lines);
for($a=0;$a<count($lines);$a++)
{
if(!empty($lines[$a]) or !ctype_space($lines[$a]))
{
//generate the line inside de Word Doc
}
}
This code works when I create the string by my own while testing the code, but won't work when the string come from a Form. And keep generating a empty line list inside the Word Doc.
When I var_dump() the $lines array it shows the last key as: [2]=> string(0) ""
I'm using Laravel and the form was created with the Form:: facade.(don't know if this matter, prob not)
If you guys could help me, I'd apreciate.
Alternatively just use array_filter with the callback of trim to remove elements that are empty or contain spaces before you iterate.
<?php
$string = '|foo|bar|baz|bat|';
$split = explode('|', $string);
$split = array_filter($split, 'trim');
var_export($split);
Output:
array (
1 => 'foo',
2 => 'bar',
3 => 'baz',
4 => 'bat',
)
However you might not want to remove some empty values!
You could just trim off your pipes to begin with:
<?php
$string = '|foo|bar|baz|bat|';
$string = trim($string, '|');
$split = explode('|', $string);
var_export($split);
Output as above.
Or use rtrim.
You may want to use PHP's && (and) rather than or.
For reference, see Logical Operators.
You only want to output the line if both empty() and ctype_space() return false. With your current code, blank strings will pass your if test because ctype_space() returns false even though empty() does not. Strings made up entirely of spaces will also pass because empty() returns false even though ctype_space() does not.
To correct the logic:
if(!empty($lines[$a]) && !ctype_space($lines[$a])) { ... }
Alternatively, I'd suggest trimming white space from the string before checking empty():
$lines = explode("|",$lines);
if (!empty($lines)) {
foreach ($lines as $line) {
if (!empty(trim($line)) {
// output this line
}
}
}
Also, see 'AND' vs '&&' as operator.
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.
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.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
If string only contains spaces?
I do not want to change a string nor do I want to check if it contains white space. I want to check if the entire string is ONLY white space. What the best way to do that?
This will be the fastest way:
$str = ' ';
if (ctype_space($str)) {
}
Returns false on empty string because empty is not white-space. If you need to include an empty string, you can add || $str == '' This will still result in faster execution than regex or trim.
ctype_space
since trim returns a string with whitespace removed, use that to check
if (trim($str) == '')
{
//string is only whitespace
}
if( trim($str) == "" )
// the string is only whitespace
This should do the trick.
preg_match('/^\s*$/',$string)
change * to + if empty is not allowed