substr_count
substr_count() возвращает число вхождений подстроки needle в строку haystack . Заметьте, что параметр needle чувствителен к регистру.
Замечание:
Эта функция не подсчитывает перекрывающиеся подстроки. Смотрите пример ниже!
Список параметров
Строка, в которой ведётся поиск
Смещение начала отсчёта. Если задано отрицательное значение, отсчёт позиции будет произведён с конца строки.
Максимальная длина строки, в которой будет производится поиск подстроки после указанного смещения. Если сумма смещения и максимальной длины будет больше длины haystack , то будет выведено предупреждение. Отрицательное значение будет отсчитываться с конца haystack .
Возвращаемые значения
Эта функция возвращает целое число ( int ).
Список изменений
Версия | Описание |
---|---|
8.0.0 | length теперь допускает значение null. |
7.1.0 | Добавлена поддержка отрицательных значений offset и length . length теперь также может быть 0 . |
Примеры
Пример #1 Пример использования substr_count()
$text = ‘This is a test’ ;
echo strlen ( $text ); // 14
?php
echo substr_count ( $text , ‘is’ ); // 2
// строка уменьшается до ‘s is a test’, поэтому вывод будет 1
echo substr_count ( $text , ‘is’ , 3 );
// текст уменьшается до ‘s i’, поэтому вывод будет 0
echo substr_count ( $text , ‘is’ , 3 , 3 );
// генерирует предупреждение, так как 5+10 > 14
echo substr_count ( $text , ‘is’ , 5 , 10 );
// выводит только 1, т.к. перекрывающиеся подстроки не учитываются
$text2 = ‘gcdgcdgcd’ ;
echo substr_count ( $text2 , ‘gcdgcd’ );
?>
Смотрите также
- count_chars() — Возвращает информацию о символах, входящих в строку
- strpos() — Возвращает позицию первого вхождения подстроки
- substr() — Возвращает подстроку
- strstr() — Находит первое вхождение подстроки
User Contributed Notes 10 notes
It’s worth noting this function is surprisingly fast. I first ran it against a ~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:
substr_count ( implode( ‘,’, $haystackArray ), $needle );
array (
0 => «mystringth»,
1 => «atislong»
);
Which brings the count for $needle = «that» to 0 again.
substr_count ( implode( $haystackArray ), $needle );
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.
$number_of_full_pattern = preg_match_all(‘/(cgc)/’, «cgcgcgcgcgcgcg», $chunks);
works like the substr_count function. The variable $number_of_full_pattern has the value 3, because the default behavior of Perl compatible regular expressions is to consume the characters of the string subject that were matched by the (sub)pattern. That is, the pointer will be moved to the end of the matched substring.
But we can use the lookahead feature that disables the moving of the pointer:
$number_of_full_pattern = preg_match_all(‘/(cg(?=c))/’, «cgcgcgcgcgcgcg», $chunks);
In this case the variable $number_of_full_pattern has the value 6.
Firstly a string «cg» will be matched and the pointer will be moved to the end of this string. Then the regular expression looks ahead whether a ‘c’ can be matched. Despite of the occurence of the character ‘c’ the pointer is not moved.
a simple version for an array needle (multiply sub-strings):
function substr_count_array ( $haystack , $needle ) $count = 0 ;
foreach ( $needle as $substring ) $count += substr_count ( $haystack , $substring );
>
return $count ;
>
?>
Unicode example with «case-sensitive» option;
function substr_count_unicode ( $str , $substr , $caseSensitive = true , $offset = 0 , $length = null ) if ( $offset ) $str = substr_unicode ( $str , $offset , $length );
>
$pattern = $caseSensitive
? ‘~(?:’ . preg_quote ( $substr ) . ‘)~u’
: ‘~(?:’ . preg_quote ( $substr ) . ‘)~ui’ ;
preg_match_all ( $pattern , $str , $matches );
return isset( $matches [ 0 ]) ? count ( $matches [ 0 ]) : 0 ;
>
function substr_unicode ( $str , $start , $length = null ) return join ( » , array_slice (
preg_split ( ‘~~u’ , $str , — 1 , PREG_SPLIT_NO_EMPTY ), $start , $length ));
>
$s = ‘Ümit yüzüm gözüm. ‘ ;
print substr_count_unicode ( $s , ‘ü’ ); // 3
print substr_count_unicode ( $s , ‘ü’ , false ); // 4
print substr_count_unicode ( $s , ‘ü’ , false , 10 ); // 1
print substr_count_unicode ( $s , ‘üm’ ); // 2
print substr_count_unicode ( $s , ‘üm’ , false ); // 3
?>
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.
function toFloat($pString, $seperatorOnConflict=»f»)
$decSeperator=».»;
$thSeperator=»»;
$pString=str_replace(» «, $thSeperator, $pString);
$firstPeriod=strpos($pString, «.»);
$firstComma=strpos($pString, «,»);
if($firstPeriod!==FALSE && $firstComma!==FALSE) if($firstPeriod <$firstComma) $pString=str_replace(".", $thSeperator, $pString);
$pString=str_replace(«,», $decSeperator, $pString);
>
else $pString=str_replace(«,», $thSeperator, $pString);
>
>
else if($firstPeriod!==FALSE || $firstComma!==FALSE) $seperator=$firstPeriod!==FALSE?».»:»,»;
if(substr_count($pString, $seperator)==1) $lastPeriodOrComma=strpos($pString, $seperator);
if($lastPeriodOrComma==(strlen($pString)-4) && ($seperatorOnConflict!=$seperator && $seperatorOnConflict!=»f»)) $pString=str_replace($seperator, $thSeperator, $pString);
>
else $pString=str_replace($seperator, $decSeperator, $pString);
>
>
else $pString=str_replace($seperator, $thSeperator, $pString);
>
>
return(float)$pString;
>
stristr
Возвращает всю строку haystack начиная с первого вхождения needle включительно.
Список параметров
Строка, в которой производится поиск
До PHP 8.0.0, если параметр needle не является строкой, он преобразуется в целое число и трактуется как код символа. Это поведение устарело с PHP 7.3.0, и полагаться на него крайне не рекомендуется. В зависимости от предполагаемого поведения, параметр needle должен быть либо явно приведён к строке, либо должен быть выполнен явный вызов chr() .
Если установлен в true , stristr() возвращает часть строки haystack до первого вхождения needle (не включая needle).
needle и haystack обрабатываются без учёта регистра.
Возвращаемые значения
Возвращает указанную подстроку. Если подстрока needle не найдена, возвращается false .
Список изменений
Версия | Описание |
---|---|
8.2.0 | Преобразование регистра больше не зависит от локали, установленной с помощью функции setlocale() . Будут преобразованы только символы ASCII. Байты не ASCII-кодировке будут сравниваться по значению байта. |
8.0.0 | Передача целого числа ( int ) в needle больше не поддерживается. |
7.3.0 | Передача целого числа ( int ) в needle объявлена устаревшей. |
Примеры
Пример #1 Пример использования stristr()
$email = ‘USER@EXAMPLE.com’ ;
echo stristr ( $email , ‘e’ ); // выводит ER@EXAMPLE.com
echo stristr ( $email , ‘e’ , true ); // выводит US
?>?php
Пример #2 Проверка на вхождение строки
$string = ‘Hello World!’ ;
if( stristr ( $string , ‘earth’ ) === FALSE ) echo ‘»earth» не найдена в строке’ ;
>
// выводит: «earth» не найдена в строке
?>?php
Пример #3 Использование не строки в поиске
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Смотрите также
- strstr() — Находит первое вхождение подстроки
- strrchr() — Находит последнее вхождение символа в строке
- stripos() — Возвращает позицию первого вхождения подстроки без учёта регистра
- strpbrk() — Ищет в строке любой символ из заданного набора
- preg_match() — Выполняет проверку на соответствие регулярному выражению
User Contributed Notes 8 notes
There was a change in PHP 4.2.3 that can cause a warning message
to be generated when using stristr(), even though no message was
generated in older versions of PHP.
The following will generate a warning message in 4.0.6 and 4.2.3:
stristr(«haystack», «»);
OR
$needle = «»; stristr(«haystack», $needle);
This will _not_ generate an «Empty Delimiter» warning message in
4.0.6, but _will_ in 4.2.3:
unset($needle); stristr(«haystack», $needle);
Just been caught out by stristr trying to converting the needle from an Int to an ASCII value.
Got round this by casting the value to a string.
if( ! stristr ( $file , (string) $myCustomer -> getCustomerID () ) ) <
// Permission denied
>
?>
An example for the stristr() function:
$a = «I like php» ;
if ( stristr ( » $a » , «LikE PhP» )) print ( «According to \$a, you like PHP.» );
>
?>
It will look in $a for «like php» (NOT case sensetive. though, strstr() is case-sensetive).
For the ones of you who uses linux.. It is similiar to the «grep» command.
Actually.. «grep -i».
function stristr_reverse ( $haystack , $needle ) <
$pos = stripos ( $haystack , $needle ) + strlen ( $needle );
return substr ( $haystack , 0 , $pos );
>
$email = ‘USER@EXAMPLE.com’ ;
echo stristr_reverse ( $email , ‘er’ );
// outputs USER
I think there is a bug in php 5.3 in stristr with uppercase Ä containing other character
if you search only with täry it works, but as soon as the word is tärylä it does not. TÄRYL works fine
function aim ( $page ) if( stristr ( $_SERVER [ ‘REQUEST_URI’ ], $page )) return ‘ ‘ ;
>
>
?>
usage:
handy little bit of code I wrote to take arguments from the command line and parse them for use in my apps.
$i = implode ( » » , $argv ); //implode all the settings sent via clie
$e = explode ( «-» , $i ); // no lets explode it using our defined seperator ‘-‘
//now lets parse the array and return the parameter name and its setting
// since the input is being sent by the user via the command line
//we will use stristr since we don’t care about case sensitivity and
//will convert them as needed later.
while (list( $index , $value ) = each ( $e ))
//lets grap the parameter name first using a double reverse string
// to get the begining of the string in the array then reverse it again
// to set it back. we will also «trim» off the » default»>$param = rtrim ( strrev ( stristr ( strrev ( $value ), ‘=’ )), » keyword»>);
//now lets get what the parameter is set to.
// again «trimming» off the = sign
$setting = ltrim ( stristr ( $value , ‘=’ ), » keyword»>);
// now do something with our results.
// let’s just echo them out so we can see that everything is working
echo «Array index is » . $index . » and value is » . $value . «\r\n» ;
echo «Parameter is » . $param . » and is set to » . $setting . «\r\n\r\n» ;
?>
when run from the CLI this script returns the following.
[root@fedora4 ~]# php a.php -val1=one -val2=two -val3=threeArray index is 0 and value is a.php
Parameter is and is set to
Array index is 1 and value is val1=one
Parameter is val1 and is set to one
Array index is 2 and value is val2=two
Parameter is val2 and is set to two
Array index is 3 and value is val3=three
Parameter is val3 and is set to three