PHP Find all occurrences of a substring in a string

后端 未结 9 1824
执念已碎
执念已碎 2020-12-01 01:56

I need to parse an HTML document and to find all occurrences of string asdf in it.

I currently have the HTML loaded into a string variable. I would just

相关标签:
9条回答
  • 2020-12-01 02:14

    Salman A has a good answer, but remember to make your code multibyte-safe. To get correct positions with UTF-8, use mb_strpos instead of strpos:

    function strpos_all($haystack, $needle) {
        $offset = 0;
        $allpos = array();
        while (($pos = mb_strpos($haystack, $needle, $offset)) !== FALSE) {
            $offset   = $pos + 1;
            $allpos[] = $pos;
        }
        return $allpos;
    }
    print_r(strpos_all("aaa bbb aaa bbb aaa bbb", "aa"));
    
    0 讨论(0)
  • 2020-12-01 02:18

    You can call the strpos function repeatedly until a match is not found. You must specify the offset parameter.

    Note: in the following example, the search continues from the next character instead of from the end of previous match. According to this function, aaaa contains three occurrences of the substring aa, not two.

    function strpos_all($haystack, $needle) {
        $offset = 0;
        $allpos = array();
        while (($pos = strpos($haystack, $needle, $offset)) !== FALSE) {
            $offset   = $pos + 1;
            $allpos[] = $pos;
        }
        return $allpos;
    }
    print_r(strpos_all("aaa bbb aaa bbb aaa bbb", "aa"));
    

    Output:

    Array
    (
        [0] => 0
        [1] => 1
        [2] => 8
        [3] => 9
        [4] => 16
        [5] => 17
    )
    
    0 讨论(0)
  • 2020-12-01 02:22
    function getocurence($chaine,$rechercher)
            {
                $lastPos = 0;
                $positions = array();
                while (($lastPos = strpos($chaine, $rechercher, $lastPos))!== false)
                {
                    $positions[] = $lastPos;
                    $lastPos = $lastPos + strlen($rechercher);
                }
                return $positions;
            }
    
    0 讨论(0)
  • 2020-12-01 02:23

    Use preg_match_all to find all occurrences.

    preg_match_all('/(\$[a-z]+)/i', $str, $matches);
    

    For further reference check this link.

    0 讨论(0)
  • 2020-12-01 02:25

    Its better to use substr_count . Check out on php.net

    0 讨论(0)
  • 2020-12-01 02:29

    This can be done using strpos() function. The following code is implemented using for loop. This code is quite simple and pretty straight forward.

    <?php
    
    $str_test = "Hello World! welcome to php";
    
    $count = 0;
    $find = "o";
    $positions = array();
    for($i = 0; $i<strlen($str_test); $i++)
    {
         $pos = strpos($str_test, $find, $count);
         if($pos == $count){
               $positions[] = $pos;
         }
         $count++;
    }
    foreach ($positions as $value) {
        echo '<br/>' .  $value . "<br />";
    }
    
    ?>
    
    0 讨论(0)
提交回复
热议问题