Check if string is just white space? [duplicate] - php

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

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 if string contains characters NOT in array [duplicate]

This question already has answers here:
How to check if a string contains certain characters using an array in php
(5 answers)
Closed 12 months ago.
I want to validate that a string consists of numbers or commas or semicolons:
valid: 1.234
valid: 1,234
invalid: 1.23a
invalid: 1.2_4
What works:
use str_split to create an array out of the string and use in_array with array(0,1,2,3,4,5,6,7,8,9,',',';').
But this feels circuitous to me and since I have to do this with millions of strings I want to make sure there is no more efficient way.
Question: Is there a more efficient way?
If you only need to validate a string (not sanitize or modify it), you can use regex. Try the following:
if (preg_match('/^[0-9\,\;\.]+$/', $string)) {
// ok
} else {
// not ok
}
The solution using preg_match function:
// using regexp for (numbers OR commas OR semicolons) - as you've required
function isValid($str) {
return (bool) preg_match("/^([0-9.]|,|;)+$/", $str);
}
var_dump(isValid("1.234")); // bool(true)
var_dump(isValid("1.23a")); // bool(false)
var_dump(isValid("1,234")); // bool(true)

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.

How to Remove a specific character from the end of the string in php or regex [duplicate]

This question already has answers here:
Removing the last character of a string IF it is $variable [duplicate]
(5 answers)
Closed 12 months ago.
I am generating a string dynamically. For example The string looks like this
$string = "this-is-a-test-string-for-example-";
It can also be like this
$string = "this-is-a-test-string-for-example";
I want if there is a hyphen "-" at the end of the string, It should be removed. How can I do that in php or regex?
http://pl1.php.net/trim - that function gets characters to trim as last parameter
trim($string,"-");
or as suggested for right side only
rtrim($string,"-");
If it always at the end (right) of the string this will work
$string = rtrim($string,"-");
$cleanedString = preg_replace('/^(this-is-a-test-string-for-example)-$/', '$1', $string);
$delete = array('-');
if(in_array($string[(strlen($string)-1)], $delete))
$string = substr($string, 0, strlen($string)-1);
You can add other characters to delete into $delete array.

How to get rid of string elements in php? [duplicate]

This question already has answers here:
Extract a single (unsigned) integer from a string
(23 answers)
Closed 11 months ago.
Customer id literal has customer_id+Domain_details, eg.: 998787+nl and now I just want to have 998787 and not +nl, how can this be acheived this in php
Question:
I have number like 9843324+nl and now I want to get rid of all elements including + and afterwards at the end and only have 9843324 and so how should I do this in php ?
Right now I am having $o_household->getInternalId returns me 9843324+nl but I want 9843324, how can I achieve this ?
Thanks.
Thanks.
Update :
list($customer_id) = explode('+',$o_household->getInternalId());
Will this solve my problem ?
If you don't want to keep the leading zeros, simply convert it into an integer.
$theID = (int)"9843324+nl";
// $theID should now be 9843324.
If the + is just a separator and the sutff before can be a non-number, use
$val = "9843324+nl";
$theID = substr($val, 0, strcspn($val, '+'));
// $theID should now be "9843324".
Easy way? Just cast it to an int and it will drop off the extra stuff.
<?php
$s = '998787+nl';
echo (int)$s;
?>
Output:
998787
<?php
$plusSignLoc = strpos($o_household->getInternalId, "+");
$myID = substr($o_household->getInternalId, 0, $plusSignLoc);
//Debug (Verification)
echo $myID;
?>
This will find the + sign, and insure that anything and everything after it will be removed.
If you need it to remain a string value, you can use substr to cut the string down to its starting index to the 3rd from last character, omitting the domain details +nl
$customer_id = substr($o_household->getInternalId, 0, -3);
As a slightly more general solution, this regular expression will remove everything that isn't a digit from the string $str and put the new string (set of numbers, so it can be treated as an integer) into $num
$num = preg_replace('/[^\d]/', '', $str);
Check out the explode() function, and use + as your delimiter.

Categories