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.
Related
I have this autogenerated variable:
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
How can I search and save "9999" in this var? I cant use substr cause $var's value is always changing and it is always in another "place" in the variable. It is always 4 numbers.
You can match 4 numbers wrapped by word boundaries or space characters, depending on what you need with regular expression (regex/regexp).
if( preg_match('/\b([0-9]{4})\b/', $var, $matches) > 0 ) {
// $matches[1] contains the number
}
Note, however, that the word boundary match will also match on non-letter characters (symbols like dollar sign ($), hyphen (-), period (.), comma (,), etc.). So a string of "XYZ ABC 9843-AB YZV" would match the "9843". If you want to just match based on numbers surrounded by white space (spaces, tabs, etc) you can use:
if( preg_match('/(?:^|\s)([0-9]{4})(?:\s|$)/', $var, $matches) > 0 ) {
// $matches[1] contains the number
}
Using explode is the way to go, we need to turn the string into an array, our variables are separated by white space, so we get a variable every time we face a white space " ", i made another example to understand how explode works.
<?php
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
print_r (explode(" ",$var)); //Display the full array.
$var_search = explode(" ",$var);
echo $var_search[3];//To echo the 9999 (4th position).
?>
<br>
<?php
$var = "WXYZ+300700Z+32011KT+9999+FEW035+SCT200+24/16+Q1007+NOSIG";
print_r (explode("+",$var)); //Display the full array.
$var_search = explode("+",$var);
echo $var_search[3];//To echo the 9999 (4th position).
?>
I hop this is what you're looking for
Is this viable?
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
if (strpos($var, '9999') == true {
// blah blah
}
else{
echo 'Value not found'
}
Personally haven't tested this yet, but I think you're looking for something along these lines...
Hello I would use a preg_match regex using this regular expression : \d{4}
here is the solution
var str1 = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
var str2 = "9999";
if(str1.indexOf(str2) != -1){
console.log(str2 + " found");
}
Small problem:
$content='/p test some text';
when "/p" is in front of the line the string should be exploded to an array
if(preg_match('^(/p)',$content)==true) {
$private=explode(" ",$content,3);
}
i think their is an error, but i've no idea for the correct search parameter
This should work for you:
(No need to compare it with true, because if it doesn't find anything it returns an empty array, which then is false. Also you need delimiters for your regex and escape the slash with a backslash)
$content='/p test some text';
if(preg_match('/^\/p/',$content)) {
//^ ^ See delimiters
$private=explode(" ",$content,3);
}
Why not a simple test
if ($content{0} == '/' && $content{1} == 'p' ) {
$private=explode(" ",$content,3);
}
I am creating a simple checker function in PHP to validate strings before putting them into an SQL query. But I can not get the right results the from the preg_match function.
$myval = "srg845s4hs64f849v8s4b9s4vs4v165";
$tv = preg_match('/[^a-z0-9]/', $myval);
echo $tv;
Sometimes nothing echoed to the source code, not even a false value... I want to get 1 as the result of this call, because $myval only contains lowercase alphanumerics and numbers.
So is there any way in php to detect if a string only contains lowercase alphanumerics and numbers using the preg_match function?
Yes, the circumflex goes outside the [] to indicate the start of the string, you probably need an asterisk to allow an arbitrary number of characters, and you probably want a $ at the end to indicate the end of the string:
$tv = preg_match('/^[a-z0-9]*$/', $myval);
If you write [^a-z] it means anything else than a-z.
If you want to test if a string contains lowercase alphanumerics only, I would present your code that way to get the proper results (what you wrote already works):
$myval = "srg845s4hs64f849v8s4b9s4vs4v165";
$tv = preg_match('/[^a-z0-9]/', $myval);
if($tv === 0){
echo "the string only contains lowercase alphanumerics";
}else if($tv === 1){
echo "the string does not only contain lowercase alphanumerics";
}else{
echo "error";
}
I need to check a string to determine if it contains any characters other than |, in order to assign those variables that have nothing except | a value of NULL (there could be theoretically any number of | characters but it likely will not be more than 5-6). Like ||||
I could see looping through each character of the string or somesuch, but I feel there must be a simpler way.
if (preg_match('/[^|]/', $string)) {
// string contains characters other than |
}
or:
if (strlen(str_replace('|', '', $string)) > 0) {
// string contains characters other than |
}
Yes, you can use regular expressions:
if(! preg_match('/[^\|]/', $string)) {
$string = NULL;
}
I wanted to check if a string only contains certain characters. To prevent double negation (because I find them harder te read) I decided to use the following regex:
preg_match('/^[|]+$/', $string)
This checks a string from beginning to end to only contain | characters (at least one).
If the string has length after trimming pipes from the front of the string, then it has at least one non-pipe character.
if (strlen(ltrim($string, '|')) {
// has non-pipe characters
}
Fastest and simplest way is possibly the stripos function. It returns the position of a string inside another, or false if it can't be found:
if (false === stripos($string, '|')) {
$string = null;
}
The false === is needed for strict type comparison, since stripos could return a zero indicating that the | is on the first char.
You can use a more sophisticated validation engine that makes reading easier. I do recommend Respect\Validation. Usage sample:
if (v::not(v::contains('|'))->validate($string)) {
$string = null;
}
i need to write a case which only except the a-zA-Z0-9 characters with underscore and white space(1 or more than 1) and ignore all rest of the characters.I wrote a code but its not working properly.
In those case should be wrong but its show OK
1) test msg#
2) test#msg
3) test!msg
also those should be OK but currently shows wrong.
1) test msg.-(Two white space)
what i should to change in my code .pls help and see my code below.
$message=$_GET['msg'];
if(preg_match('/[^A-Za-z0-9]\W/',$message))
{
echo "Wrong";
}
else
{
echo "OK";
}
Here's an optimized version of the one left by riad:
$message = $_GET['msg'];
if ( preg_match('/^[a-z0-9_ ]+$/i', $message) )
{
echo 'Ok';
}
else
{
echo 'Wrong';
}
I've removed the A-Z (uppercase) from the regular expression since the i modifier is used.
I'd also like to explain what you did wrong in the example you provided.
First, by putting the ^ inside the square brackets ([]), you're essentially doing the opposite of what you were trying to do. Place a ^ inside the square brackets means "not including."
You were missing a *, + or ? at the end of the square bracket, unless you only wanted to match a single character. The * character means 0 or more, + means 1 or more and ? means 0 or 1.
The \W means any non-word character. That's probably not what you wanted.
Finally, to starting a regular expression with ^ means that the beginning of the string you're string to match must start with whatever is after the ^. Ending the regular expression with a $ means that the string must end with the characters preceding the $.
So by typing /^[a-z0-9_ ]+$/i you're saying match a string that starts with a-z0-9_ or a space, that contains at least of those characters (+) and ends.
PHP has a lot of documentation of the PCRE regular syntax which you can find here: http://ca2.php.net/manual/en/reference.pcre.pattern.syntax.php.
$message=$_GET['msg'];
if(preg_match('/^[a-zA-Z0-9_ ]+$/i',$message))
{
echo "Wrong";
}
else
{
echo "OK";
}