Get string between - Find all occurrences PHP

前端 未结 6 1432
抹茶落季
抹茶落季 2020-12-08 16:37

I found this function which finds data between two strings of text, html or whatever.

How can it be changed so it will find all occurrences? Every data between every

6条回答
  •  攒了一身酷
    2020-12-08 16:51

    One possible approach:

    function getContents($str, $startDelimiter, $endDelimiter) {
      $contents = array();
      $startDelimiterLength = strlen($startDelimiter);
      $endDelimiterLength = strlen($endDelimiter);
      $startFrom = $contentStart = $contentEnd = 0;
      while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) {
        $contentStart += $startDelimiterLength;
        $contentEnd = strpos($str, $endDelimiter, $contentStart);
        if (false === $contentEnd) {
          break;
        }
        $contents[] = substr($str, $contentStart, $contentEnd - $contentStart);
        $startFrom = $contentEnd + $endDelimiterLength;
      }
    
      return $contents;
    }
    

    Usage:

    $sample = 'OneaaaTwoTwoThreeFourFive';
    print_r( getContents($sample, '', '') );
    /*
    Array
    (
        [0] => One
        [1] => TwoTwo
        [2] => Four
        [3] => Five
    )
    */ 
    

    Demo.

提交回复
热议问题