Посчитать количество подстрок php

PHP substr_count() Function

what is the syntax of the SUBSTR_COUNT() function in php?

substr_count(string,substring,start,length)
Parameter Description
string Required. Specifies the string to check
substring Required. Specifies the string to search for
start Optional. Specifies where in string to start searching. If negative, it starts counting from the end of the string
length Optional. Specifies the length of the search

PHP SUBSTR_COUNT() method

examples of the SUBSTR_COUNT() function

Example 1. In this example, we count the number of times “world” occurs in the string.

Example 2. In this example, we use all parameters.

"; // Using strlen() to return the string length echo substr_count($str,"is")."
"; // The number of times "is" occurs in the string echo substr_count($str,"is",2)."
"; // The string is now reduced to "is is nice" echo substr_count($str,"is",3)."
"; // The string is now reduced to "s is nice" echo substr_count($str,"is",3,3)."
"; // The string is now reduced to "s i" ?>

Example 3. In this example, we overlapped substrings.

Example 3. In this example, if we the start and length parameters exceeds the string length, this function will output a warning.

Читайте также:  Graphic objects in java

Источник

substr_count

substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.

Note:

This function doesn’t count overlapped substrings. See the example below!

Parameters

The substring to search for

The offset where to start counting. If the offset is negative, counting starts from the end of the string.

The maximum length after the specified offset to search for the substring. It outputs a warning if the offset plus the length is greater than the haystack length. A negative length counts from the end of haystack .

Return Values

This function returns an int .

Changelog

Version Description
8.0.0 length is nullable now.
7.1.0 Support for negative offset s and length s has been added. length may also be 0 now.

Examples

Example #1 A substr_count() example

$text = ‘This is a test’ ;
echo strlen ( $text ); // 14

echo substr_count ( $text , ‘is’ ); // 2

// the string is reduced to ‘s is a test’, so it prints 1
echo substr_count ( $text , ‘is’ , 3 );

// the text is reduced to ‘s i’, so it prints 0
echo substr_count ( $text , ‘is’ , 3 , 3 );

// generates a warning because 5+10 > 14
echo substr_count ( $text , ‘is’ , 5 , 10 );

// prints only 1, because it doesn’t count overlapped substrings
$text2 = ‘gcdgcdgcd’ ;
echo substr_count ( $text2 , ‘gcdgcd’ );
?>

See Also

  • count_chars() — Return information about characters used in a string
  • strpos() — Find the position of the first occurrence of a substring in a string
  • substr() — Return part of a string
  • strstr() — Find the first occurrence of a string

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;
>

Источник

substr_count

substr_count() возвращает число вхождений подстроки needle в строку haystack . Заметьте, что параметр needle чувствителен к регистру.

Замечание:

Эта функция не подсчитывает перекрывающиеся подстроки. Смотрите пример ниже!

Список параметров

Строка, в которой ведется поиск

Максимальная длина строки в которой будет производится поиск подстроки после указанного смещения. Если сумма смещения и максимальной длины будет больше длины haystack , то будет выведено предупреждение.

Возвращаемые значения

Список изменений

Версия Описание
5.1.0 Добавлены параметры offset и length

Примеры

Пример #1 Пример использования substr_count()

$text = ‘This is a test’ ;
echo strlen ( $text ); // 14

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() — Находит первое вхождение подстроки

Источник

mb_substr_count

Подсчитывает, сколько раз подстрока needle встречается в строке haystack .

Список параметров

Строка ( string ) для проверки

Строка ( string ) для поиска

Параметр encoding представляет собой символьную кодировку. Если он опущен или равен null , вместо него будет использовано значение внутренней кодировки.

Возвращаемые значения

Количество вхождений подстроки needle в строку haystack .

Список изменений

Примеры

Пример #1 Пример использования mb_substr_count()

Смотрите также

  • mb_strpos() — Поиск позиции первого вхождения одной строки в другую
  • mb_substr() — Возвращает часть строки
  • substr_count() — Возвращает число вхождений подстроки

User Contributed Notes

  • Функции для работы с многобайтовыми строками
    • mb_​check_​encoding
    • mb_​chr
    • mb_​convert_​case
    • mb_​convert_​encoding
    • mb_​convert_​kana
    • mb_​convert_​variables
    • mb_​decode_​mimeheader
    • mb_​decode_​numericentity
    • mb_​detect_​encoding
    • mb_​detect_​order
    • mb_​encode_​mimeheader
    • mb_​encode_​numericentity
    • mb_​encoding_​aliases
    • mb_​ereg_​match
    • mb_​ereg_​replace_​callback
    • mb_​ereg_​replace
    • mb_​ereg_​search_​getpos
    • mb_​ereg_​search_​getregs
    • mb_​ereg_​search_​init
    • mb_​ereg_​search_​pos
    • mb_​ereg_​search_​regs
    • mb_​ereg_​search_​setpos
    • mb_​ereg_​search
    • mb_​ereg
    • mb_​eregi_​replace
    • mb_​eregi
    • mb_​get_​info
    • mb_​http_​input
    • mb_​http_​output
    • mb_​internal_​encoding
    • mb_​language
    • mb_​list_​encodings
    • mb_​ord
    • mb_​output_​handler
    • mb_​parse_​str
    • mb_​preferred_​mime_​name
    • mb_​regex_​encoding
    • mb_​regex_​set_​options
    • mb_​scrub
    • mb_​send_​mail
    • mb_​split
    • mb_​str_​split
    • mb_​strcut
    • mb_​strimwidth
    • mb_​stripos
    • mb_​stristr
    • mb_​strlen
    • mb_​strpos
    • mb_​strrchr
    • mb_​strrichr
    • mb_​strripos
    • mb_​strrpos
    • mb_​strstr
    • mb_​strtolower
    • mb_​strtoupper
    • mb_​strwidth
    • mb_​substitute_​character
    • mb_​substr_​count
    • mb_​substr

    Источник

    PHP substr_count() Function

    Count the number of times «world» occurs in the string:

    The substr_count() function counts the number of times a substring occurs in a string.

    Note: The substring is case-sensitive.

    Note: This function does not count overlapped substrings (see example 2).

    Note: This function generates a warning if the start parameter plus the length parameter is greater than the string length (see example 3).

    Syntax

    Parameter Values

    Parameter Description
    string Required. Specifies the string to check
    substring Required. Specifies the string to search for
    start Optional. Specifies where in string to start searching. If negative, it starts counting from the end of the string
    length Optional. Specifies the length of the search

    Technical Details

    Return Value: Returns the the number of times the substring occurs in the string
    PHP Version: 4+
    Changelog: PHP 7.1 — The length parameters can be 0 or a negative number.
    PHP 7.1 — The start parameters can be a negative number.
    PHP 5.1 — The start and length parameters were added.

    More Examples

    Example

    $str = «This is nice»;
    echo strlen($str).»
    «; // Using strlen() to return the string length
    echo substr_count($str,»is»).»
    «; // The number of times «is» occurs in the string
    echo substr_count($str,»is»,2).»
    «; // The string is now reduced to «is is nice»
    echo substr_count($str,»is»,3).»
    «; // The string is now reduced to «s is nice»
    echo substr_count($str,»is»,3,3).»
    «; // The string is now reduced to «s i»
    ?>

    Example

    $str = «abcabcab»;
    echo substr_count($str,»abcab»); // This function does not count overlapped substrings
    ?>

    Example

    If the start and length parameters exceeds the string length, this function will output a warning:

    This will output a warning because the length value exceeds the string length (3+9 is greater than 12)

    Источник

Оцените статью