An explode() function that ignores characters inside quotes?

后端 未结 3 2054
挽巷
挽巷 2020-12-11 04:14

Does somebody know a quick and easy explode() like function that can ignore splitter characters that are enclosed in a pair of arbitrary characters (e.g. quotes

3条回答
  •  一个人的身影
    2020-12-11 04:50

    This is near-impossible with preg_split, because you can't tell from the middle of the string whether you're between quotes or not. However, preg_match_all can do the job.

    Simple solution for a single type of quote:

    function quoted_explode($subject, $delimiter = ',', $quote = '\'') {
        $regex = "(?:[^$delimiter$quote]|[$quote][^$quote]*[$quote])+";
        preg_match_all('/'.str_replace('/', '\\/', $regex).'/', $subject, $matches);
        return $matches[0];
    }
    

    That function will have all kinds of problems if you pass it certain special characters (\^-], according to http://www.regular-expressions.info/reference.html), so you'll need to escape those. Here's a general solution that escapes special regex characters and can track multiple kinds of quotes separately:

    function regex_escape($subject) {
        return str_replace(array('\\', '^', '-', ']'), array('\\\\', '\\^', '\\-', '\\]'), $subject);
    }
    
    function quoted_explode($subject, $delimiters = ',', $quotes = '\'') {
        $clauses[] = '[^'.regex_escape($delimiters.$quotes).']';
        foreach(str_split($quotes) as $quote) {
            $quote = regex_escape($quote);
            $clauses[] = "[$quote][^$quote]*[$quote]";
        }
        $regex = '(?:'.implode('|', $clauses).')+';
        preg_match_all('/'.str_replace('/', '\\/', $regex).'/', $subject, $matches);
        return $matches[0];
    }
    

    (Note that I keep all of the variables between square brackets to minimize what needs escaping - outside of square brackets, there are about twice as many special characters.)

    If you wanted to use ] as a quote, then you probably wanted to use [ as the corresponding quote, but I'll leave adding that functionality as an exercise for the reader. :)

提交回复
热议问题