php посчитать количество цифр в строке
substr_count
(PHP 4, PHP 5, PHP 7, PHP 8)
substr_count — Возвращает число вхождений подстроки
Описание
Эта функция не подсчитывает перекрывающиеся подстроки. Смотрите пример ниже!
Список параметров
Строка, в которой ведётся поиск
Смещение начала отсчёта. Если задано отрицательное значение, отсчёт позиции будет произведён с конца строки.
Возвращаемые значения
Эта функция возвращает целое число ( int ).
Список изменений
Примеры
Пример #1 Пример использования substr_count()
Смотрите также
User Contributed Notes 10 notes
500KB string on our web server. It found 6 occurrences of the needle I was looking for in 0.0000 seconds. Yes, it ran faster than microtime() could measure.
Looking to give it a challenge, I then ran it on a Mac laptop from 2010 against a 120.5MB string. For one test needle, it found 2385 occurrences in 0.0266 seconds. Another test needs found 290 occurrences in 0.114 seconds.
Long story short, if you’re wondering whether this function is slowing down your script, the answer is probably not.
Making this case insensitive is easy for anyone who needs this. Simply convert the haystack and the needle to the same case (upper or lower).
To account for the case that jrhodes has pointed out, we can change the line to:
array (
0 => «mystringth»,
1 => «atislong»
);
It was suggested to use
instead of the function described previously, however this has one flaw. For example this array:
array (
0 => «mystringth»,
1 => «atislong»
);
If you are counting «that», the implode version will return 1, but the function previously described will return 0.
Yet another reference to the «cgcgcgcgcgcgc» example posted by «chris at pecoraro dot net»:
Your request can be fulfilled with the Perl compatible regular expressions and their lookahead and lookbehind features.
This will handle a string where it is unknown if comma or period are used as thousand or decimal separator. Only exception where this leads to a conflict is when there is only a single comma or period and 3 possible decimals (123.456 or 123,456). An optional parameter is passed to handle this case (assume thousands, assume decimal, decimal when period, decimal when comma). It assumes an input string in any of the formats listed below.
below was suggested a function for substr_count’ing an array, yet for a simpler procedure, use the following:
Unicode example with «case-sensitive» option;
In regards to anyone thinking of using code contributed by zmindster at gmail dot com
Please take careful consideration of possible edge cases with that regex, in example:
This would cause a infinite loop and for example be a possible entry point for a denial of service attack. A correct fix would require additional code, a quick hack would be just adding a additional check, without clarity or performance in mind:
ctype_digit
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
ctype_digit — Проверяет наличие цифровых символов в строке
Описание
Проверяет, являются ли все символы в строке text цифровыми.
Список параметров
Возвращаемые значения
Примеры
Пример #1 Пример использования ctype_digit()
Результат выполнения данного примера:
Пример #2 Пример использования ctype_digit() со сравнением строк и целых чисел
Смотрите также
User Contributed Notes 14 notes
All basic PHP functions which i tried returned unexpected results. I would just like to check whether some variable only contains numbers. For example: when i spread my script to the public i cannot require users to only use numbers as string or as integer. For those situation i wrote my own function which handles all inconveniences of other functions and which is not depending on regular expressions. Some people strongly believe that regular functions slow down your script.
The reason to write this function:
1. is_numeric() accepts values like: +0123.45e6 (but you would expect it would not)
2. is_int() does not accept HTML form fields (like: 123) because they are treated as strings (like: «123»).
3. ctype_digit() excepts all numbers to be strings (like: «123») and does not validate real integers (like: 123).
4. Probably some functions would parse a boolean (like: true or false) as 0 or 1 and validate it in that manner.
ctype_digit() will treat all passed integers below 256 as character-codes. It returns true for 48 through 57 (ASCII ‘0’-‘9’) and false for the rest.
(Note: the PHP type must be an int; if you pass strings it works as expected)
count
(PHP 4, PHP 5, PHP 7, PHP 8)
count — Подсчитывает количество элементов массива или чего-либо в объекте
Описание
Подсчитывает количество элементов массива или чего-то в объекте.
Смотрите раздел Массивы в этом руководстве для более детального представления о реализации и использовании массивов в PHP.
Список параметров
Если необязательный параметр mode установлен в COUNT_RECURSIVE (или 1), count() будет рекурсивно подсчитывать количество элементов массива. Это особенно полезно для подсчёта всех элементов многомерных массивов.
count() умеет определять рекурсию для избежания бесконечного цикла, но при каждом обнаружении выводит ошибку уровня E_WARNING (в случае, если массив содержит себя более одного раза) и возвращает большее количество, чем могло бы ожидаться.
Возвращаемые значения
Список изменений
Примеры
Пример #1 Пример использования count()
Результат выполнения данного примера:
var_dump ( count ( null ));
var_dump ( count ( false ));
?>
Результат выполнения данного примера:
Результат выполнения данного примера в PHP 7.2:
Результат выполнения данного примера в PHP 8:
Пример #3 Пример рекурсивного использования count()
Смотрите также
User Contributed Notes 17 notes
[Editor’s note: array at from dot pl had pointed out that count() is a cheap operation; however, there’s still the function call overhead.]
If you are on PHP 7.2+, you need to be aware of «Changelog» and use something like this:
My function returns the number of elements in array for multidimensional arrays subject to depth of array. (Almost COUNT_RECURSIVE, but you can point on which depth you want to plunge).
I actually find the following function more useful when it comes to multidimension arrays when you do not want all levels of the array tree.
$arr [ ‘__been_here’ ] = true ;
to end the debate: count() is the same as empty()
results on my computer:
count : double(0.81396999359131)
empty : double(0.81621310710907)
using isset($test[0]) is a bit slower than empty;
test without adding value to the array in function ****Test: still the same.
A function of one line to find the number of elements that are not arrays, recursively :
Get maxWidth and maxHeight of a two dimensional array.
Note:
1st dimension = Y (height)
2nd dimension = X (width)
e.g. rows and cols in database result arrays
You can not get collect sub array count when there is only one sub array in an array:
$a = array ( array (‘a’,’b’,’c’,’d’));
$b = array ( array (‘a’,’b’,’c’,’d’), array (‘e’,’f’,’g’,’h’));
echo count($a); // 4 NOT 1, expect 1
echo count($b); // 2, expected
For a Non Countable Objects
Warning: count(): Parameter must be an array or an object that implements Countable in example.php on line 159
#Quick fix is to just cast the non-countable object as an array..
As I see in many codes, don’t use count to iterate through array.
Onlyranga says you could declare a variable to store it before the for loop.
I agree with his/her approach, using count in the test should be used ONLY if you have to count the size of the array for each loop.
You can not get collect sub array count when use the key on only one sub array in an array:
$a = array(«a»=>»appple», b»=>array(‘a’=>array(1,2,3),’b’=>array(1,2,3)));
$b = array(«a»=>»appple», «b»=>array(array(‘a’=>array(1,2,3),’b’=>array(1,2,3)), array(1,2,3),’b’=>array(1,2,3)), array(‘a’=>array(1,2,3),’b’=>array(1,2,3))));
echo count($a[‘b’]); // 2 NOT 1, expect 1
echo count($b[‘b’]); // 3, expected
To get the count of the inner array you can do something like:
$inner_count = count($array[0]);
echo ($inner_count);
About 2d arrays, you have many way to count elements :
Criada para contar quantos níveis um array multidimensional possui.
/* Verifica se o ARRAY foi instanciado */
if (is_setVar($matrix))<
/* Verifica se a variável é um ARRAY */
if(is_array($matrix))<
In special situations you might only want to count the first level of the array to figure out how many entries you have, when they have N more key-value-pairs.
If you want to know the sub-array containing the MAX NUMBER of values in a 3 dimensions array, here is a try (maybe not the nicest way, but it works):
$cat_poids_max[‘M’][‘Seniors’][] = 55;
$cat_poids_max[‘M’][‘Seniors’][] = 60;
$cat_poids_max[‘M’][‘Seniors’][] = 67;
$cat_poids_max[‘M’][‘Seniors’][] = 75;
$cat_poids_max[‘M’][‘Seniors’][] = 84;
$cat_poids_max[‘M’][‘Seniors’][] = 90;
$cat_poids_max[‘M’][‘Seniors’][] = 100;
//.
$cat_poids_max[‘F’][‘Juniors’][] = 52;
$cat_poids_max[‘F’][‘Juniors’][] = 65;
$cat_poids_max[‘F’][‘Juniors’][] = 74;
$cat_poids_max[‘F’][‘Juniors’][] = 100;
is_numeric
(PHP 4, PHP 5, PHP 7, PHP 8)
is_numeric — Проверяет, является ли переменная числом или строкой, содержащей число
Описание
Определяет, является ли данная переменная числом или строкой, содержащей число.
Список параметров
Возвращаемые значения
Примеры
Пример #1 Примеры использования is_numeric()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 40 notes
If you want the numerical value of a string, this will return a float or int value:
Note that the function accepts extremely big numbers and correctly evaluates them.
So this function is not intimidated by super-big numbers. I hope this helps someone.
PS: Also note that if you write is_numeric (45thg), this will generate a parse error (since the parameter is not enclosed between apostrophes or double quotes). Keep this in mind when you use this function.
for strings, it return true only if float number has a dot
is_numeric( ‘42.1’ )//true
is_numeric( ‘42,1’ )//false
I think that is best check solution if u want to create real calculator for example 🙂
is_number ( 12 ); // true
is_number (- 12 ); // true
is_number (- 12.2 ); // true
is_number ( «12» ); // true
is_number ( «-124.3» ); // true
is_number ( 0.8 ); // true
is_number ( «0.8» ); // true
is_number ( 0 ); // true
is_number ( «0» ); // true
is_number ( NULL ); // false
is_number ( true ); // false
is_number ( false ); // false
is_number ( «324jdas32» ); // false
is_number ( «123-» ); // false
is_number ( 1e7 ); // true
is_number ( «1e7» ); // true
is_number ( 0x155 ); // true
is_number ( «0x155» ); // false
?>
check if given string is mobile number
Referring to previous post «Be aware if you use is_numeric() or is_float() after using set_locale(LC_ALL,’lang’) or set_locale(LC_NUMERIC,’lang’)»:
This is totally wrong!
This was the example code:
——
set_locale(LC_NUMERIC,’fr’);
is_numeric(12.25); // Return False
is_numeric(12,25); // Return True
is_float(12.25); //Return False
is_float(12,25); //Return True
——
— set_locale() does not exist, you must use setlocale() instead
— you have to enclose 12,25 with quotes; otherwise PHP will think that
the function gets _two_ arguments: 12 and 25 (depending on PHP version and setup you may additionally get a PHP warning)
— if you don’t enclose 12,25 with quotes the first argument will be the inspected value (12), the second value (25) is discarded. And is_numeric(12) and is_float(12) is always TRUE
—-
setlocale(LC_NUMERIC,’fr’);
is_numeric(12.25); // Return True
is_numeric(«12,25»); // Return False
is_float(12.25); //Return True
is_float(«12,25»); //Return False
—-
Remarks:
— is_float(12.25) is _always_ TRUE, 12.25 is a PHP language construct (a «value») and the way PHP interpretes files is definitely _not_ affected by the locale
— is_float(«12,25») is _always_ FALSE, since is_float (other than is_numeric): if the argument is a string then is_float() always returns FALSE since it does a strict check for floats
And the corrected example shows: you get the _same_ results for every possible locale, is_numeric() does not depend on the locale.
/* This function is not useful if you want
to check that someone has filled in only
numbers into a form because for example
4e4 and 444 are both «numeric».
I used a regular expression for this problem
and it works pretty good. Maybe it is a good
idea to write a function and then to use it.
$input_number = «444»; // Answer 1
$input_number = «44 «; // Answer 2
$input_number = «4 4»; // Answer 2
$input_number = «4e4»; // Answer 2
$input_number = «e44»; // Answer 2
$input_number = «e4e»; // Answer 2
$input_number = «abc»; // Answer 2
*/
$input_number = «444» ;
The solution is pretty simple and no subroutines or fancy operations are necessary to make the ‘is_numeric’ function usable for form entry checks:
Simply strip off all (invisible) characters that may be sent along with the value when submitting a form entry.
Just use the ‘trim’ function before ‘is_numeric’.
Two simple functions using is_numeric:
?>
And here is the result:
1: odd? TRUE
0: odd? FALSE
6: odd? FALSE
«italy»: odd? FALSE
null: odd? FALSE
1: even? FALSE
0: even? TRUE
6: even? TRUE
«italy»: even? FALSE
null: even? FALSE
Here’s a function to determine if a variable represents a whole number:
just simple stuff.
is_whole_number(2.00000000001); will return false
is_whole_number(2.00000000000); will return true
If you want detect integer of float values, which presents as pure int or float, and presents as string values, use this functions:
Sometimes, we need to have no letters in the number and is_numeric does not quit the job.
You can try it this ways to make sure of the number format:
function new_is_unsigned_float($val) <
$val=str_replace(» «,»»,trim($val));
return eregi(«^(1)+([\.|,](9)*)?$»,$val);
>
function new_is_unsigned_integer($val) <
$val=str_replace(» «,»»,trim($val));
return eregi(«^(6)+$»,$val);
>
function new_is_signed_float($val) <
$val=str_replace(» «,»»,trim($val));
return eregi(«^-?(6)+([\.|,](1)*)?$»,$val);
>
function new_is_signed_integer($val) <
$val=str_replace(» «,»»,trim($val));
return eregi(«^-?(4)+$»,$val);
>
It returns 1 if okay and returns nothing «» if it’s bad number formating.
I needed a number_suffix function that takes numbers with thousand seperators (using number_format() function). Note that this doesn’t properly handle decimals.
Also, increasing the range above the condition statements increases efficiency. That’s almost 20% of the numbers between 0 and 100 that get to end early.
Maybe your function was more strickt, but profides FALSE to any numeric string that wasnt written in the English/American notition. To enable a person to use the both the English/American and the rest of the world’s way:
(*Note:
-the E/A way of writing 1 million (with decimal for 1/50): 1,000,000.02
-the global way of writing 1 million (with decimal for 1/50): 1.000.000,02
Here’s an even simpler pair of functions for finding out if a number is odd or even:
if(IS_ODD($myNumber))
echo(«number is odd\n»);
else
echo(«number is NOT odd\n»);
if(IS_even($myNumber))
echo(«number is even\n»);
else
echo(«number is NOT even\n»);
Results:
number is odd
number is NOT even
Here is a simple function that I found usefull for filtering user input into numbers. Basically, it attempts to fix fat fingering. For example:
The output in this case would be ‘654.45’.
Please note that this function will work properly unless the user fat fingers an extra decimal in the wrong place.
When using the exec() function in php to execute anther php script, any command line arguments passed the script will lose their type association, regardless of whether they are numeric or not, the same seems to hold true for strings as well.
ie : two scripts test.php:
Note that this function is not appropriate to check if «is_numeric» for very long strings. In fact, everything passed to this function is converted to long and then to a double. Anything greater than approximately 1.8e308 is too large for a double, so it becomes infinity, i.e. FALSE. What that means is that, for each string with more than 308 characters, is_numeric() will return FALSE, even if all chars are digits.
However, this behaviour is platform-specific.
In such a case, it is suitable to use regular expressions:
I find it a little weird that people are having issues with ordinal numbers, it’s pretty easy..
Notes are in the commenting, check out the example outputs.
var_dump ( ordinal ( 5 ));
ordinal(‘-1’); returns false because ctype_digit hates anything that
isn’t strictly 0 through 9 and ‘-‘ trips it to false.
ordinal(‘asdf’); returns false for the exact same reason.
ordinal(); returns false because it’s blank.
signed integers on a 32-bit system (and the same issue on a 64-bit
system using 0x7FFFFFFFFFFFFFFF because of two’s compliment,
anything higher will become a negative number):
ordinal(0x7FFFFFFF ); returns 2147483647th (which is correct)
ordinal(0x7FFFFFFF+1); returns false.
*/
strlen
(PHP 4, PHP 5, PHP 7, PHP 8)
strlen — Возвращает длину строки
Описание
Список параметров
Строка ( string ), для которой измеряется длина.
Возвращаемые значения
Примеры
Пример #1 Пример использования strlen()
Примечания
Функция strlen() возвратит количество байт, а не число символов в строке.
Смотрите также
User Contributed Notes 8 notes
I want to share something seriously important for newbies or beginners of PHP who plays with strings of UTF8 encoded characters or the languages like: Arabic, Persian, Pashto, Dari, Chinese (simplified), Chinese (traditional), Japanese, Vietnamese, Urdu, Macedonian, Lithuanian, and etc.
As the manual says: «strlen() returns the number of bytes rather than the number of characters in a string.», so if you want to get the number of characters in a string of UTF8 so use mb_strlen() instead of strlen().
// the Arabic (Hello) string below is: 59 bytes and 32 characters
$utf8 = «السلام علیکم ورحمة الله وبرکاته!» ;
The easiest way to determine the character count of a UTF8 string is to pass the text through utf8_decode() first:
We just ran into what we thought was a bug but turned out to be a documented difference in behavior between PHP 5.2 & 5.3. Take the following code example:
?>
This is because in 5.2 strlen will automatically cast anything passed to it as a string, and casting an array to a string yields the string «Array». In 5.3, this changed, as noted in the following point in the backward incompatible changes in 5.3 (http://www.php.net/manual/en/migration53.incompatible.php):
«The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error.»
So, in PHP 5.3, strlen($attributes) returns NULL, while in PHP 5.2, strlen($attributes) returns the integer 5. This likely affects other functions, so if you are getting different behaviors or new bugs suddenly, check if you have upgraded to 5.3 (which we did recently), and then check for some warnings in your logs like this:
strlen() expects parameter 1 to be string, array given in /var/www/sis/lib/functions/advanced_search_lib.php on line 1028
If so, then you are likely experiencing this changed behavior.
When checking for length to make sure a value will fit in a database field, be mindful of using the right function.
There are three possible situations:
1. Most likely case: the database column is UTF-8 with a length defined in unicode code points (e.g. mysql varchar(200) for a utf-8 database).
Find the character set used, and pass it explicitly to the length function.
There’s a LOT of misinformation here, which I want to correct! Many people have warned against using strlen(), because it is «super slow». Well, that was probably true in old versions of PHP. But as of PHP7 that’s definitely no longer true. It’s now SUPER fast!
I created a 20,00,000 byte string (
20 megabytes), and iterated ONE HUNDRED MILLION TIMES in a loop. Every loop iteration did a new strlen() on that very, very long string.
The result: 100 million strlen() calls on a 20 megabyte string only took a total of 488 milliseconds. And the strlen() calls didn’t get slower/faster even if I made the string smaller or bigger. The strlen() was pretty much a constant-time, super-fast operation
So either PHP7 stores the length of every string as a field that it can simply always look up without having to count characters. Or it caches the result of strlen() until the string contents actually change. Either way, you should now never, EVER worry about strlen() performance again. As of PHP7, it is super fast!
Here is the complete benchmark code if you want to reproduce it on your machine: