Get string between - Find all occurrences PHP

前端 未结 6 1431
抹茶落季
抹茶落季 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:56

    I also needed the text outside the pattern. So I changed the answer from raina77ow above a little:

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

    Usage:

        $str = "Bore layer thickness [2 mm] instead of [1,25 mm] with [0,1 mm] deviation.";
        $cas = get_delimited_strings($str, "[", "]");
    

    gives:

    array(2) { 
        ["in"]=> array(3) { 
            [0]=> string(4) "2 mm" 
            [1]=> string(7) "1,25 mm" 
            [2]=> string(6) "0,1 mm" 
        } 
        ["out"]=> array(4) { 
            [0]=> string(21) "Bore layer thickness " 
            [1]=> string(12) " instead of " 
            [2]=> string(6) " with " 
            [3]=> string(10) " deviation" 
        } 
    }
    

提交回复
热议问题