PHP Find all occurrences of a substring in a string

后端 未结 9 1839
执念已碎
执念已碎 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:37

    Without using regex, something like this should work for returning the string positions:

    $html = "ffffdasdfffffdasdffff";
    $needle = "asdf";
    $lastPos = 0;
    $positions = array();
    
    while (($lastPos = strpos($html, $needle, $lastPos))!== false) {
        $positions[] = $lastPos;
        $lastPos = $lastPos + strlen($needle);
    }
    
    // Displays 3 and 10
    foreach ($positions as $value) {
        echo $value ."
    "; }

提交回复
热议问题