I was looking for a quick PHP function that, given a string, would count the number of numerical characters (i.e. digits) in that string. I couldn't find one, is there a function to do this?
This can easily be accomplished with a regular expression.
function countDigits( $str )
{
return preg_match_all( "/[0-9]/", $str );
}
The function will return the amount of times the pattern was found, which in this case is any digit.
first split your string, next filter the result to only include numeric chars and then simply count the resulting elements.
<?php
$text="12aap33";
print count(array_filter(str_split($text),'is_numeric'));
edit: added a benchmark
out of curiosity: (loop of 1000000 of above string and routines)
preg_based.php is overv's preg_match_all solution
harald#Midians_Gate:~$ time php filter_based.php
real 0m20.147s
user 0m15.545s
sys 0m3.956s
harald#Midians_Gate:~$ time php preg_based.php
real 0m9.832s
user 0m8.313s
sys 0m1.224s
the regular expression is clearly superior. :)
For PHP < 5.4:
function countDigits( $str )
{
return count(preg_grep('~^[0-9]$~', str_split($str)));
}
This function goes through the given string and checks each character to see if it is numeric. If it is, it increments the number of digits, then returns it at the end.
function countDigits($str) {
$noDigits=0;
for ($i=0;$i<strlen($str);$i++) {
if (is_numeric($str{$i})) $noDigits++;
}
return $noDigits;
}
Related
I made this function to check if the first character is a letter.
function isLetter($string) {
return preg_match('/^\s*[a-z,A-Z]/', $string) > 0;
}
However, if I check a sentence that starts with a coma (,) the functions returns true. What is the proper regex to check if the first letter is a-z or A-Z?
You just need to remove the comma:
'/^\s*[a-zA-Z]/'
A slightly cleaner way, in my opinion. Just makes the code a little more human readable.
function isLetter($string) {
return preg_match('/^[a-z]/i', trim($string));
}
This question already has answers here:
php validate integer
(7 answers)
Closed 9 years ago.
Hey I'm trying to perform input validation in PHP to ensure that the stock values that are typed in are at least 1 positive integer and from 0-9. Should not contain any special characters.
For example, any of the following values should be valid:
7
0
32
47534
The following SHOULD NOT be valid:
asdf
35/gdf
../34.
etc..
I'm using the following if statement to check for the positive integer value of "$original_stock".
if (preg_match("/^[0-9]$/", $original_stock))
{
$error .="Original stock must be numerical.";
}
Additionally, I have a price field which should be validated as either an int or a double.
If there's an easier alternative to using regex, that's okay too!
Thanks in advance :)
Try this regexp:
/^\d+$/
The issue with your existing regexp is that it only matches strings with exactly one digit.
As for validating an int or a double:
/^\d+\.?\d*$/
Note that that regexp requires that there be at least one digit.
Use:
/^[0-9]+$/
The + means "one or more". Without it, your regex will only match a single digit. Or you could use the simpler variant:
/^\d+$/
For floats, try something like:
/^\d+(\.\d{1,2})?/
This will match one or more digits, optionally followed by a . and one or two digits. (i.e. .12 will not match.)
To save yourself some headaches, you can also use the is_int and is_float functions.
Lastly; note that your check is wrong. preg_match will return 0 if it fails, so you should write it as:
if (!preg_match("/^\+$/", $original_stock)) {
// error
}
(note the !).
You may want to use the
is_int
Don't reinvent a wheel slower than an existing one, use a motorcycle: is_int.
#Assuming $original_stock is a single value...
if (is_int($original_stock)) {
#Valid, do stuff
}
else {
#Invalid, do stuff
}
#Assuming $original_stock is an array...
$valid = true;
foreach ($original_stock as $s) {
if (!is_int($s)) {
$valid = false;
break;
}
}
if ($valid) {...}
else {...}
I just ran into this exact problem and solved it this way using the regex.
I think the problem is your caret ^.
/^[0-9]$/
I moved it inside the class and got the results I needed.
function validate_int($subject)
{
//Pattern is numbers
//if it matches anything but numbers, we want a fail
$pattern = '/[^0-9]/';
$matches = preg_match($pattern, $subject);
if($matches > 0)
return false;
else
return true;
}
I have a database of more than 70000 records and its primary key value started from 1 single digit.
So I want user have to type nm0000001 instead of 1 in url.And in code part I have to discard the rest of the value except 1.
But my problem is i want this type of things having 9 letters in the string and the pattern is like this
1 - nm0000001
9 - nm0000009
10 - nm0000010
2020 - nm0002020
And from the above pattern i want only the digits like 1,9,10,2020 in php.
Here:
$i = (int)substr($input, 2);
No reason to use regexes at all.
Anyway, if you're insisting on using regexp, then:
$input = 'nm0002020';
preg_match('~0*(\d+)$~', $input, $matches);
var_dump($matches[1]);
Assuming the value is received in the URL as a querystring parameter, that is, passed via $_GET['id'] or some other name than id:
// Trim the "nm" off the front
$pk = substr($_GET['id'],2);
// And parse out an integer value.
$id = intval($pk);
There's absolutely no use for regular expressions in this -- use sprintf("nm%07d", ...) to format and just substr and a cast to int to parse.
This function will do the trick:
function extractID($pInput)
{
$Matches = array();
preg_match('/^nm0*(.*)$/', $pInput, $Matches);
return intval($Matches[1]);
}
Here's why /^nm0+(.*)$/ works:
The line must start (^) with exactly one nm
The pattern must continue with at least one 0
At the first non-zero character after nm0..., capture the value (that's the job of the parentheses)
Continue until the end of the line ($)
I'm trying to port this java to php:
String _value = '1111122222';
if (_value.matches("(1{5}|2{5}|3{5}|4{5}|5{5}|6{5}|7{5}|8{5}|9{5}){2}")) {
// check for number with the same first 5 and last 5 digits
return true;
}
As the comment suggests, I want to test for a string like '1111122222' or '5555566666'
How can I do this in PHP?
Thanks,
Scott
You can use preg_match to do so:
preg_match('/^(1{5}|2{5}|3{5}|4{5}|5{5}|6{5}|7{5}|8{5}|9{5}){2}$/', $_value)
This returns the number of matches (i.e. either 0 or 1) or false if there was an error. Since the String’s matches method returns only true if the whole string matches the given pattern but preg_match doesn’t (a substring suffices), you need to set markers for the start and the end of the string with ^ and $.
You can also use this shorter regular expression:
^(?:(\d)\1{4}){2}$
And if the second sequence of numbers needs to be different from the former, use this:
^(\d)\1{4}(?!\1)(\d)\2{4}$
Well, you could do:
$regex = '/(\d)\1{4}(\d)\2{4}/';
if (preg_match($regex, $value)) {
return true;
}
Which should be much more efficient (and readable) than the regex you posted...
Or, an even shorter (and potentially cleaner) regex:
$regex = '/((\d)\2{4}){2}/';
$f = substr($_value, 0, 5);
$s = substr($_value, -5);
return (substr_count($f, $f[0]) == 5 && substr_count($s, $s[0]) == 5);
Conversion is below. preg_match() is the key: http://www.php.net/preg_match
$value = '1111122222';
if (preg_match('/^(1{5}|2{5}|3{5}|4{5}|5{5}|6{5}|7{5}|8{5}|9{5}){2}$/', $value)) {
// check for number with the same first 5 and last 5 digits
return true;
}
Is there a Php function to determine if a string consist of only ASCII alphanumerical characters?
Note: I'm sorry if the question sounds dumb to some, but I couldn't easily find such a function in the Php manual.
Try ctype_alnum
preg_match('/^[a-z0-9]+$/i', $str);
Edit: John T's answer is better. Just providing another method.
This is my solution
<?php
public function alphanum($string){
if(function_exists('ctype_alnum')){
$return = ctype_alnum($string);
}else{
$return = preg_match('/^[a-z0-9]+$/i', $string) > 0;
}
return $return;
}
?>
My long, but simple solution
strspn($string, '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM_') == strlen($string)
Function strspn() finds the length of the initial segment of $string that contains only letters, numbers and underscore character (second argument). If entire string consists only of letters, numbers and underscore, the returned value will be equeal to the length of the string.