Check if variable has a number php - php

I want to check if a variable has a number in it, I just want to see if there is one I don't care if it has any thing else in it like so:
"abc" - false
"!./#()" - false
"!./#()abc" - false
"123" - true
"abc123" - true
"!./#()123" - true
"abc !./#() 123" -true
There are easy ways of doing this if you want to know that is all numbers but not if it just has one. Thanks for your help.

You can use the strcspn function:
if (strcspn($_REQUEST['q'], '0123456789') != strlen($_REQUEST['q']))
echo "true";
else
echo "false";
strcspn returns the length of the part that does not contain any integers. We compare that with the string length, and if they differ, then there must have been an integer.
There is no need to invoke the regular expression engine for this.

$result = preg_match("/\\d/", $yourString) > 0;

Holding on to spirit of #Martin, I found a another function that works in similar fashion.
(strpbrk($var, '0123456789')
e.g. test case
<?php
function a($var) {
return (strcspn($var, '0123456789') != strlen($var));
}
function b($var) {
return (strpbrk($var, '0123456789'));
}
$var = array("abc", "!./#()", "!./#()abc", "123", "abc123", "!./#()123", "abc !./#() 123");
foreach ($var as $v) {
echo $v . ' = ' . b($v) .'<hr />';
}
?>

This should help you:
$numberOfNumbersFound = preg_match("/[0-9]+/", $yourString);
You could get more out of the preg_match function, so have a look at its manual

you can use this pattern to test your string using regular expressions:
$isNumeric = preg_match("/\S*\d+\S*/", $string) ? true : false;

Related

Check if whole string contains same character

I want to check if a string contains a character repeated zero or more times, for example:
If my string is aaaaaa, bbbb, c or ***** it must return true.
If it contains aaab, cd, or **%*** it must return false.
In other words, if the string has 2 or more unique characters, it must return false.
How to go about this in PHP?
PS: Is there a way to do it without RegEx?
You could split on every character then count the array for unique values.
if(count(array_count_values(str_split('abaaaa'))) == 1) {
echo 'True';
} else {
echo 'false';
}
Demo: https://eval.in/760293
count(array_unique(explode('', string)) == 1) ? true : false;
You can use a regular expression with a back-reference:
if (preg_match('/^(.)\1*$/', $string)) {
echo "Same characters";
}
Or a simple loop:
$same = true;
$firstchar = $string[0];
for ($i = 1; $i < strlen($string); $i++) {
if ($string[$i] != $firstchar) {
$same = false;
break;
}
}
For the fun of it:
<?php
function str2Dec($string) {
$hexstr = unpack('H*', $string);
$hex = array_shift($hexstr);
return hexdec($hex);
}
function isBoring($string) {
return str2Dec($string) % str2Dec(substr($string, 0, 1)) === 0;
}
$string1 = 'tttttt';
$string2 = 'ttattt';
var_dump(isBoring($string1)); // => true
var_dump(isBoring($string2)); // => false
Obviously this works only in small strings because once it gets big enough, the INT will overflow and the mod will not produce the correct value. So, don't use this :) - posting it just to show a different idea from the usual ones.
strlen(str_replace($string[0], '', $string)) ? false : true;
You can check that the number of unique characters is greater than 1. This will perform well even if the input string is empty: (Demo)
$string = 'aaaba';
var_export(
strlen(count_chars($string, 3)) < 2 // false
);
Alternatively, you can trim the string by its first character, but this will generate warnings/notices if the input string has no length. (Demo)
$string = 'aaaba';
var_export(
!strlen(trim($string, $string[0])) // false
);
p.s. Yes, you could use !strlen(trim($string, #$string[0])) to prevent warnings/notices caused by a zero-length string, but I avoid error suppression like the plague because it generally gives code a bad smell.
Regex: ^(.)\1{1,}
^: Starting of string
(.): Match and capture single characted.
\1{1,}: using captured character one or more than once.
For this you can use regex
OR:
PHP code demo
$string="bbbb";
if($length=strlen($string))
{
substr_count($string,$string[0]);
if($length==substr_count($string,$string[0]))
{
echo "Do something";
}
}

PHP - Check if a string contains any of the chars in another string

How can I check if a string contains any of the chars in another string with PHP?
$a = "asd";
$b = "ds";
if (if_first_string_contains_any_of_the_chars_in_second_string($a, $b)) {
echo "Yep!";
}
So in this case, it should echo, since ASD contains both a D and an S.
I want to do this without regexes.
You can do it using
$a = "asd";
$b = "ds";
if (strpbrk($a, $b) !== FALSE)
echo 'Found it';
else
echo "nope!";
For more info check : http://php.net/manual/en/function.strpbrk.php
Second parameter is case sensitive.
+1 #hardik solanki. Also, you can use similar_text ( count/percent of matching chars in both strings).
$a = "asd";
$b = "ds";
if (similar_text($a, $b)) {
echo "Yep!";
}
Note: function is case sensitive.
you can use str_split function here, then just have a look at the given links:
this might help you,
http://www.w3schools.com/php/showphp.asp?filename=demo_func_string_str_split
http://www.w3schools.com/php/func_array_intersect.asp
try to use strpos
. Hope it helpful

PHP - How To Compare Alike Data?

In PHP, how to compare two "alike" data? For instance, in this code:
$a = "cats are cool";
$b = "1. catS are cool!!!"
if($a == $b) {
echo "TRUE";
}
else {
echo "FALSE";
}
now the obvious output will be "FALSE". But to what I'm trying to achieve, as long as the keyword "cats are cool" is in $b, the result should be "TRUE". How do I do this?
If you are looking for an exact match, use stripos().
//Note the use of !== here, it's because stripos may return 0,
//Which would be interpreted as false without strict comparison.
if (stripos($string, "cats are cool") !== false) {
//Cats are cool indeed.
}
You have to define your own logic, period. Either you look for keywords [e.g. you search how many occurrences of your whitelist pop up in your strings], or you compute some string distance metric, like Levenshtein distance.
If you should find just first string in second you can use strpos
use stripos()
if(stripos($b,$a) !== FALSE)
echo "found";
else
echo "not found";

PHP strpos to match querystring text pattern

I need to execute a bit of script only if the $_GET['page'] parameter has the text "mytext-"
Querystring is: admin.php?page=mytext-option
This is returning 0:
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
echo $match;
strpos returns the position of the string. Since it's 0, that means it was found at position 0, meaning, at the start of the string.
To make an easy way to understand if it's there, add the boolean === to an if statement like this:
<?php
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
if ( $match === false ) {
echo 'Not found';
} else {
echo 'Found';
}
?>
This will let you know, if the string is present or not.
Or, if you just need to know, if it's there:
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
if ( $match !== false ) {
echo 'Found';
}
?>
Use substr() once you get the location of 'mytext-', like so:
$match = substr($myPage, strpos( $myPage, 'mytext-') + strlen( 'mytext-'));
Otherwise, strpos() will just return the numerical index of where 'mytext-' starts in the string.
You can also use str_replace() to accomplish this if your string only has 'mytext-' once:
$match = str_replace( 'mytext-', '', $myPage);
The function strpos() returns the position where the searched string starts which is 0. If the string is not found, the function will return false. See the strpos documentation which tells you as well:
WARNING This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
A solution to your question would be to use substr(), preg_match() or check if strpos() !== false.
The easiest solution should be this:
if (preg_match('/^mytext-/i', $_GET['page'])) {
// do something
}
You may also consider using more than just one GET parameter like
http://www.example.com/foo.php?page=mysite&option1=123&option2=456
You then use your parameters lik $_GET['page'], $_GET['option1'], $_GET['option2'], etc.
However, you should also be careful what you do with raw $_GETor $_POST data since users can directly input them and may inject harmful code to your website.
That is expected since the substring starts at index 0. Read the warning on php.net/strpos:
Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
If you only need to check if $myPage contains 'mytext-', use stristr:
if(stristr($myPage, 'mytext-') !== false) {
// contains..
}
What's wrong about preg_match?
$myPage = $_GET['page'];
if (preg_match("/\bmytext-\b/i", $myPage)) {
//Do Something
}
Or do you need the "option" out of "mytext-option"?
If yes you can use this:
$myPage = $_GET['page'];
$querystrings = explode("-", $myPage);
if ($querystrings[0] == 'mytext')) {
//Do Something
echo $querystrings[1]; //outputs option
}
With this you can even use more "options" in your querystring like "mytext-option-whatever". That's the same as when you use
$_GET['page'], $_GET['option'], $_GET['whatever']
when you use
?page=mysite&option=x&whatever=y

PHP: intval() equivalent for numbers >= 2147483647

In PHP 5, I use intval() whenever I get numbers as an input. This way, I want to ensure that I get no strings or floating numbers. My input numbers should all be in whole numbers. But when I get numbers >= 2147483647, the signed integer limit is crossed.
What can I do to have an intval() equivalent for numbers in all sizes?
Here's what I want to have:
<?php
$inputNumber = 3147483647.37;
$intNumber = intvalEquivalent($inputNumber);
echo $intNumber; // output: 3147483647
?>
Thank you very much in advance!
Edit: Based on some answers, I've tried to code an equivalent function. But it doesn't work exactly as intval() does yet. How can I improve it? What is wrong with it?
function intval2($text) {
$text = trim($text);
$result = ctype_digit($text);
if ($result == TRUE) {
return $text;
}
else {
$newText = sprintf('%.0f', $text);
$result = ctype_digit($newText);
if ($result == TRUE) {
return $newText;
}
else {
return 0;
}
}
}
Try this function, it will properly remove any decimal as intval does and remove any non-numeric characters.
<?php
function bigintval($value) {
$value = trim($value);
if (ctype_digit($value)) {
return $value;
}
$value = preg_replace("/[^0-9](.*)$/", '', $value);
if (ctype_digit($value)) {
return $value;
}
return 0;
}
// SOME TESTING
echo '"3147483647.37" : '.bigintval("3147483647.37")."<br />";
echo '"3498773982793749879873429874.30872974" : '.bigintval("3498773982793749879873429874.30872974")."<br />";
echo '"hi mom!" : '.bigintval("hi mom!")."<br />";
echo '"+0123.45e6" : '.bigintval("+0123.45e6")."<br />";
?>
Here is the produced output:
"3147483647.37" : 3147483647
"3498773982793749879873429874.30872974" : 3498773982793749879873429874
"hi mom!" : 0
"+0123.45e6" : 0
Hope that helps!
you can also use regular expressions to remove everything after the intial numeric parts:
<?php
$inputNumber = "3147483647.37";
$intNumber = preg_replace('/^([0-9]*).*$/', "\\1", $inputNumber);
echo $intNumber; // output: 3147483647
?>
Either use number_format($inputNumber, 0, '', '')
Or if you only want to check if its a whole number then use ctype_digit($inputNumber)
Don't use the proposed is_numeric, as also floats are numeric. e.g. "+0123.45e6" gets accepted by is_numeric
In addition to number_format, you can use sprintf:
sprintf("%.0f", 3147483647.37) // 3147483647
However, both solutions suffer from float overflow, for example:
sprintf("%.0f", 314734534534533454346483647.37) // 314734534534533440685998080
If you want to handle arbitrary-precision numbers, you will need to use the gmp extension. The function gmp_init(), for example, converts a string to a gmp resource object. the drawback is that you must use other functions of that extension to further process that object. Converting it back to a string is done using gmp_strval(), for example.
$gmpObject = gmp_init($string, 10);
if ($gmpObject === FALSE) {
# The string was not a valid number,
# handle this case here
}
echo gmp_strval($gmpObject);
You might want to only verify that the string is representing a valid number and use the string itself, if you do not intend to do any operations on the value. That can be done using a regular expression:
$containsInt = preg_match('/^\d+$/', $string);
# Or for floating point numbers:
$containsFloat = preg_match('/^\d+(.\d+)?$/', $string);
echo $string;
Another option is to use is_numeric(). But that function does more conversion than you might like. Quoting from docs of that function:
... +0123.45e6 is a valid numeric value ...
<?php
$a = 453453445435.4;
echo $bigint = floor($a);

Categories