If I have two PHP variables that are strings and one is a multi-word string while the other is a single-word string.
How can I write a custom function that returns true if the larger string contains the smaller string.
Here is what I have so far in terms of code:
function contains($smaller, $larger){
//if $smaller is in larger{
return true;
}
else{
return false;
}
How can I do the commented out part?
I can't use a regex since I don't know the exact value of $smaller, right?
This version should return a Boolean and guard against 0 vs false return
function contains($smaller, $larger){
return strpos($larger, $smaller) !== false;
}
There is a php function strstr which will return the position of the "smaller" string.
http://www.php.net/manual/en/function.strstr.php
if(strstr($smaller, $larger))
{
//Its true
}
PHP already has it. Strpos is your answer
http://php.net/manual/en/function.strrpos.php
if (strpos($larger, $smaller) !== false){
// smaller string is in larger
} else {
// does not contains
}
If it founds the string, it returns the position. Beware to check for 0 (if the position of a smaller is in the 0-th location)
Related
I have a simple function which checks if a value is a number and if that number is less than 0.
function check_number($value){
if(!is_numeric(strval($value))){
return "value must be whole or decimal";
} else {
if($value < 0){
return "value must be bigger than 0";
}
}
return "successful value";
}
This functions works all well and good, until special numbers are passed in such as:
0xf4c3b00c
1e7
These values will still make the function return "successful value".
How can I make these special numbers not return a false positive in my case.
Thanks.
function check_number($value){
if (!is_numeric($value)) {
return "That is not a number";
}
if ($value < 0) {
return "value must be bigger than 0";
}
if(!ctype_digit(str_replace('.', '', $value))){
return "value must be whole or decimal";
}
return "successful value";
}
SEE DEMO
You have peculiar requirements. Your definition of a number differs from PHP's - 4.1e7 is a number, just not one formatted in a way you like. So you need to look at the number as it appears - as a string.
Check if value is less than 0 first, because later we won't distinguish between a minus sign and any other character.
Count dots in the number string.
If more than 1 dot, return fail.
If just 1 dot, str_replace it out and continue.
Finally, use ctype_digit on the remaining string.
Change
if(!is_numeric(strval($value))){
into
$value = trim($value, "0"); // get value as string and remove leading and trailing zeroes
$value_float = ltrim(floatval($value), "0"); // get float value as string and remove leading zero
if($value !== $value_float){
or to make it compacter
if(trim($value, "0") !== ltrim(floatval($value), "0")){
to check whether the numerical representation is still the same after stringifying.
I am using the PHP filter_validate_int to perform a simple telephone validation. The length should be exactly 10 chars and all should be numeric. However as most of the telephone numbers start with a 0. The filter validate int function return false. Is there anyway to resolve this issue. Here is the code that I have used
if(!filter_var($value, FILTER_VALIDATE_INT) || strlen($value) != 10) return false;
There is nothing you can do to make this validation work. In any case, you should not be using FILTER_VALIDATE_INT because telephone numbers are not integers; they are strings of digits.
If you want to make sure that $tel is a string consisting of exactly 10 digits you can use a regular expression:
if (preg_match('/^\d{10}$/', $tel)) // it's valid
or (perhaps better) some oldschool string functions:
if (strlen($tel) == 10 && ctype_digit($tel)) // it's valid
Use preg_match
$str = '0123456789';
if(preg_match('/^\d{10}$/', $str))
{
echo "valid";
}
else
{
echo "invalid";
}
You can use regex :
if (!preg_match('~^\d{10}$~', $value)) return false;
It's a PHP bug - #43372
Regex are fine, but consume some resources.
This works fine with any integer, including zero and leading zeros
if (filter_var(ltrim($val, '0'), FILTER_VALIDATE_INT) || filter_var($val, FILTER_VALIDATE_INT) === 0) {
echo("Variable is an integer");
} else {
echo("Variable is not an integer");
}
0 is not a valid starting number for an int. 0 is the starting number of octal numbers.
A telephone number is a string, not an int. You have to use a regexp to validate it.
Probably you need to check whether the return is false or 0. The filters return the input when the validation is successful, or false when it fails.
Use strict comparison (=== or !==) for the comparison, like $result!==false.
if(filter_var($squid, FILTER_VALIDATE_INT)!==false ) {
//if it's here, it passed validation
}
You could also use the is_numeric function:
http://php.net/manual/en/function.is-numeric.php
I am trying to do a basic operation: to check whether string is a number.
This does not work:
$qty = $_REQUEST[qty];
if (is_int($qty) == FALSE) {
echo "error";
} else {
echo "ok";
}
This one does:
$qty = 1;
if (is_int($qty) == FALSE) {
echo "error";
} else {
echo "ok";
}
$_REQUEST[qty] is posted with AJAX request ($.post). $_REQUEST[qty] is NOT empty and contains only number (1).
is_numeric() is not going to work, since it treats 1e4 as a number.
is_int will only return true if the variable is of integer type.
if you are trying to test if the variable contains a string which represents a number,
use:
is_numeric("1");
source: http://php.net/manual/en/function.is-int.php
EDIT:
use ctype_digit() to check for every character in the string if it's a number to rule out "1e4"
If you want to check for the presence of digits only, you can use ctype_digit .
try "is_numeric()" instead of "is_int"...
i think that u r getting a String from your Request...
and is_int really checks wether a given object is a integer... But it isn't -> it's a String.
is_numeric just checks, wether a object is convertable into an integer. If so, it returns true, otherwise false...
$qty = $_REQUEST[qty];
if (is_numeric($qty) == FALSE) {
echo "error";
} else {
echo "ok";
}
PS: Use $_POST[] or $_GET[] insetead of $_REQUEST[] ;)
You mention you cannot use is_numeric because it treats 1e4 as a number. Well, 1e4 is a number. Specifically 1 * 10^4.
You could use is_int(intval($_REQUEST['qty'])), but as intval always returns an int (0 on failure or empty input) you run the risk of false positives. However, combined with is_numeric or filter_var you should be on pretty solid ground.
Actually, all $_REQUEST (as well as $_GET, $_POST, etc) values are always strings.
When $qty is $_REQUEST[qty] it's an string, not an integer. When $qty is 1, it's already an integer.
Use intval function to convert it to an integer. But as you say, you only want to find out whether it's an integer or not, so use floatval to convert it, then check if they are equal:
if (intval($qty) == floatval($qty)) {
echo "Ok!";
} else {
echo "error";
}
Do a not-identical comparisonĀDocs while using the string and integer cast:
if ($qty !== (string)(int)$qty) {
echo "error";
} else {
echo "ok";
}
This is basically literal: As all incoming variables are strings, you can't check them being an integer, unless you cast them to an integer and then back to string. Wrap it into a function if it's to hard to grasp in inline code what it does:
/**
* string is integer value?
*
* #return bool
*/
function is_int_string($string)
{
return $string === (string)(int)$string;
}
$qty = $_REQUEST[qty];
if (is_int_string($qty) == FALSE) {
echo "error";
} else {
echo "ok";
}
HTTP is a text protocol, so there is only string in the beginning.
I decided to go with preg_match().
if (!preg_match("/^[0-9]+$/", $_REQUEST[qty])) {}
I use this code in php to detect whether there is five same symbols in a row in the string and execute some code if it does.
function symbolsInRow($string, $limit = 5) {
$regex = '/(.)\1{'.($limit - 1).',}/us';
return 0 == preg_match($regex, $string);
}
Now I need to do the same thing in javascript, but unfortunately I'm not familiar with it enough. How can be this function converted into javascript? The function should return false if it finds 5 same symbols in row in the given string.
Here you go
function symbolsInRow(string, limit) {
// set the parameter to 5 if it is not provided
limit = (limit || 5);
// create a regexp object, initialized with the regex you want. we escape the \ with \\ because it is a special char in javascript strings.
var regex = new RegExp('(.)\\1{'+(limit-1)+',}');
// return false if we find a match (true if no match is found)
return !regex.test(string);
}
the actual test method will return true if it finds a match. So notice the ! which is the not operator inverting the result of the test, since you wanted to return false if it found a sequence.
example at http://www.jsfiddle.net/gaby/aPTAb/
May be not with a regexp:
function symbolsInRow(str, limit, symbol){
return str.split(symbol).length === limit + 1;
}
This should be equivalent:
function symbolsInRow(string, limit) {
limit = (limit || 5) - 1;
return !(new RegExp('(.)\\1{'+limit+'}')).test(string);
}
For five case-sensitive characters in a row, this should work:
function symbolsInRow(string) {
return /(.)\1{4}/.test(string);
}
If you need to match an arbitrary number of repetitions:
function symbolsInRow(string,limit) {
return (new RegExp('(.)\\1{'+limit+'}')).test(string);
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have a function isNotEmpty which returns true if the string is not empty and false if the string is empty. I've found out that it is not working if I pass an empty string through it.
function isNotEmpty($input)
{
$strTemp = $input;
$strTemp = trim($strTemp);
if(strTemp != '') //Also tried this "if(strlen($strTemp) > 0)"
{
return true;
}
return false;
}
The validation of the string using isNotEmpty is done:
if(isNotEmpty($userinput['phoneNumber']))
{
//validate the phone number
}
else
{
echo "Phone number not entered<br/>";
}
If the string is empty the else doesn't execute, I don't understand why, can someone please shed some light on this please.
Simple problem actually. Change:
if (strTemp != '')
to
if ($strTemp != '')
Arguably you may also want to change it to:
if ($strTemp !== '')
since != '' will return true if you pass is numeric 0 and a few other cases due to PHP's automatic type conversion.
You should not use the built-in empty() function for this; see comments and the PHP type comparison tables.
I always use a regular expression for checking for an empty string, dating back to CGI/Perl days, and also with Javascript, so why not with PHP as well, e.g. (albeit untested)
return preg_match('/\S/', $input);
Where \S represents any non-whitespace character
PHP have a built in function called empty()
the test is done by typing
if(empty($string)){...}
Reference php.net : php empty
In your if clause in the function, you're referring to a variable strTemp that doesn't exist. $strTemp does exist, though.
But PHP already has an empty() function available; why make your own?
if (empty($str))
/* String is empty */
else
/* Not empty */
From php.net:
Return Values
Returns FALSE if var has a non-empty
and non-zero value.
The following things are considered to
be empty:
* "" (an empty string)
* 0 (0 as an integer)
* "0" (0 as a string)
* NULL
* FALSE
* array() (an empty array)
* var $var; (a variable declared, but without a value in a class)
http://www.php.net/empty
PHP evaluates an empty string to false, so you can simply use:
if (trim($userinput['phoneNumber'])) {
// validate the phone number
} else {
echo "Phone number not entered<br/>";
}
Just use strlen() function
if (strlen($s)) {
// not empty
}
I just write my own function, is_string for type checking and strlen to check the length.
function emptyStr($str) {
return is_string($str) && strlen($str) === 0;
}
print emptyStr('') ? "empty" : "not empty";
// empty
Here's a small test repl.it
EDIT: You can also use the trim function to test if the string is also blank.
is_string($str) && strlen(trim($str)) === 0;
I needed to test for an empty field in PHP and used
ctype_space($tempVariable)
which worked well for me.
Well here is the short method to check whether the string is empty or not.
$input; //Assuming to be the string
if(strlen($input)==0){
return false;//if the string is empty
}
else{
return true; //if the string is not empty
}
You can simply cast to bool, dont forget to handle zero.
function isEmpty(string $string): bool {
if($string === '0') {
return false;
}
return !(bool)$string;
}
var_dump(isEmpty('')); // bool(true)
var_dump(isEmpty('foo')); // bool(false)
var_dump(isEmpty('0')); // bool(false)
I know this thread been pretty old but I just wanted to share one of my function. This function below can check for empty strings, string with maximum lengths, minimum lengths, or exact length. If you want to check for empty strings, just put $min_len and $max_len as 0.
function chk_str( $input, $min_len = null, $max_len = null ){
if ( !is_int($min_len) && $min_len !== null ) throw new Exception('chk_str(): $min_len must be an integer or a null value.');
if ( !is_int($max_len) && $max_len !== null ) throw new Exception('chk_str(): $max_len must be an integer or a null value.');
if ( $min_len !== null && $max_len !== null ){
if ( $min_len > $max_len ) throw new Exception('chk_str(): $min_len can\'t be larger than $max_len.');
}
if ( !is_string( $input ) ) {
return false;
} else {
$output = true;
}
if ( $min_len !== null ){
if ( strlen($input) < $min_len ) $output = false;
}
if ( $max_len !== null ){
if ( strlen($input) > $max_len ) $output = false;
}
return $output;
}
if you have a field namely serial_number and want to check empty then
$serial_number = trim($_POST[serial_number]);
$q="select * from product where user_id='$_SESSION[id]'";
$rs=mysql_query($q);
while($row=mysql_fetch_assoc($rs)){
if(empty($_POST['irons'])){
$irons=$row['product1'];
}
in this way you can chek all the fileds in the loop with another empty function
this is the short and effective solution, exactly what you're looking for :
return $input > null ? 'not empty' : 'empty' ;
You got an answer but in your case you can use
return empty($input);
or
return is_string($input);