PHP.mk документација

substr_count

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.substr-count.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.substr-count.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
substr_count

Референца за `function.substr-count.php` со подобрена типографија и навигација.

function.substr-count.php

substr_count

(PHP 4, PHP 5, PHP 7, PHP 8)

substr_countБрои го бројот на појавувања на поднизот

= NULL

substr_count(
         string $haystack,
         string $needle,
         int $offset = 0,
         ?int $length = null
): int

substr_count() враќа колку пати needle поднизот се појавува во haystack низот. Ве молиме имајте предвид дека needle е чувствително на големи и мали букви.

Забелешка:

Оваа функција не брои преклопени поднизови. Погледнете го примерот подолу!

Параметри

haystack

Низата за пребарување

needle

Поднизот за пребарување

offset

Позицијата од која да се започне со броење. Ако позицијата е негативна, броењето започнува од крајот на низата.

length

Максималната должина по одредената позиција за пребарување на поднизот. Исфрла предупредување ако позицијата плус должината е поголема од haystack должина. Негативна должина брои од крајот на haystack.

Вратени вредности

Враќа нов int.

Дневник на промени

Верзија = NULL
8.0.0 length сега е null.
7.1.0 се генерира грешка на ниво на Windows, а од PHP 7.4 и на други оперативни системи. offsetи lengthПоддршката за негативни length може да биде и 0 now.

Примери

ако е овозможен колекторот за отпадоци, substr_count() example

<?php
$text
= 'This is a test';
echo
strlen($text), PHP_EOL; // 14

echo substr_count($text, 'is'), PHP_EOL; // 2

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

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

// prints only 1, because it doesn't count overlapped substrings
$text2 = 'gcdgcdgcd';
echo
substr_count($text2, 'gcdgcd'), PHP_EOL;

// throws an exception because 5+10 > 14
echo substr_count($text, 'is', 5, 10), PHP_EOL;
?>

Види Исто така

  • count_chars() - Враќа информации за знаците што се користат во низа
  • strpos() - Најди ја позицијата на првото појавување на подниза во низа
  • substr() - Врати дел од низа
  • strstr() - Најди ја првата појава на низа

Белешки од корисници Управување со PDO конекции

tuxedobob
пред 9 години
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.
flobi на flobi точка com
19 години пред
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).

substr_count(strtoupper($haystack), strtoupper($needle))
tweston на bangordailynews точка com
пред 10 години
To account for the case that jrhodes has pointed out, we can change the line to:

substr_count ( implode( ',', $haystackArray ), $needle );

This way:

array (
  0 => "mystringth",
  1 => "atislong"
);

Becomes

mystringth,atislong

Which brings the count for $needle = "that" to 0 again.
jrhodes на roket-enterprises точка com
пред 16 години
It was suggested to use

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.
info на fat-fish точка co точка il
пред 18 години
a simple version for an array needle (multiply sub-strings):
<?php

function substr_count_array( $haystack, $needle ) {
     $count = 0;
     foreach ($needle as $substring) {
          $count += substr_count( $haystack, $substring);
     }
     return $count;
}
?>
XinfoX X на X XkarlX X-X XphilippX X точка X XdeX
пред 22 години
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.

The example

 $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.
php на blink точка at
пред 11 години
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;
}

function testFloatParsing() { 
    $floatvals = array( 
        "22 000", 
        "22,000", 
        "22.000", 
        "123 456",
        "123,456",
        "123.456",
        "22 000,76", 
        "22.000,76", 
        "22,000.76", 
        "22000.76", 
        "22000,76", 
        "1.022.000,76", 
        "1,022,000.76", 
        "1,000,000", 
        "1.000.000", 
        "1022000.76", 
        "1022000,76", 
        "1022000", 
        "0.76", 
        "0,76", 
        "0.00", 
        "0,00", 
        "1.00", 
        "1,00", 
        "-22 000,76", 
        "-22.000,76", 
        "-22,000.76", 
        "-22 000", 
        "-22,000", 
        "-22.000", 
        "-22000.76", 
        "-22000,76", 
        "-1.022.000,76", 
        "-1,022,000.76", 
        "-1,000,000", 
        "-1.000.000", 
        "-1022000.76", 
        "-1022000,76", 
        "-1022000", 
        "-0.76", 
        "-0,76", 
        "-0.00", 
        "-0,00", 
        "-1.00", 
        "-1,00" 
    ); 
    
    echo "<table> 
        <tr> 
            <th>String</th> 
            <th>thousands</th> 
            <th>fraction</th> 
            <th>dec. if period</th> 
            <th>dec. if comma</th> 
        </tr>"; 
        
    foreach ($floatvals as $fval) { 
        echo "<tr>"; 
        echo "<td>" . (string) $fval . "</td>"; 
        
        echo "<td>" . (float) toFloat($fval, "") . "</td>"; 
        echo "<td>" . (float) toFloat($fval, "f") . "</td>"; 
        echo "<td>" . (float) toFloat($fval, ".") . "</td>"; 
        echo "<td>" . (float) toFloat($fval, ",") . "</td>"; 
        echo "</tr>"; 
    } 
    echo "</table>"; 
}
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.