Use PHP for splitting on spaces and brackets

后端 未结 5 853
醉梦人生
醉梦人生 2021-01-21 09:03

I have this string in $s:

ben say (#yellow) hey

At the moment I\'m using:

$parts = array_filter(preg_sp         


        
相关标签:
5条回答
  • 2021-01-21 09:30

    this will work:

    $parts = array_filter(preg_split('/[\s\(\)]+/', $s));
    
    0 讨论(0)
  • 2021-01-21 09:33

    Well you can try this replacement:

    $s = str_replace(array('(', ')'), array('( ', ' )'), $s);
    $parts = array_filter(preg_split('/\s+/', $s));
    

    The trick here is to add a space between your ( and the word so that it gets splitted. However, it will only work specific to your example. Things like (( might cause some unwanted results. If so you can try using preg_replace instead.

    0 讨论(0)
  • 2021-01-21 09:38

    You could split it by Lookahead and Lookbehind Zero-Width Assertions:

    $parts = array_filter(preg_split('/\s+|(?=[()])|(?<=[()])/', $s));
    
    0 讨论(0)
  • 2021-01-21 09:49
    <?php
    
    // function to explode on multiple delimiters
    function multi_explode($pattern, $string, $standardDelimiter = ':')
    {
        // replace delimiters with standard delimiter, also removing redundant delimiters
        $string = preg_replace(array($pattern, "/{$standardDelimiter}+/s"), $standardDelimiter, $string);
    
        // return the results of explode
        return explode($standardDelimiter, $string);
    }
    
    // test
    
        // set up variables
        $string = "zero  one | two :three/ four\ five:: six|| seven eight nine\n ten \televen twelve thirteen fourteen fifteen";
        $pattern = '/[:\|\\\\\/\s]/';  // colon (:), pipe (escaped '\|'), slashes (escaped '\\\\' and '\/'), white space (\s)
    
        // call function
        $result = multi_explode($pattern, $string);
    
        // display results
        var_dump($result);
    
    ?>
    

    Source : http://php.net/manual/en/function.explode.php Examples

    0 讨论(0)
  • 2021-01-21 09:49

    A one liner which will work exactly as wanted (you don't even need array_filter):

    $s = "ben say (ewfs) as";
    $parts = preg_split('/\s+|(\()|(\))/', $s, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)
    
    /*
    Array(
      0 => "ben",
      1 => "say",
      2 => "(",
      3 => "ewfs",
      4 => ")",
      5 => "as",
    )
    */
    
    0 讨论(0)
提交回复
热议问题