parse search string for phrases and keywords

后端 未结 3 2026
滥情空心
滥情空心 2021-02-04 14:41

i need to parse a search string for keywords and phrases in php, for example

string 1: value of \"measured response\" detect goal \"method valuation\" study

3条回答
  •  一生所求
    2021-02-04 15:36

    $s = 'value of "measured response" detect goal "method valuation" study';
    preg_match_all('~(?|"([^"]+)"|(\S+))~', $s, $matches);
    print_r($matches[1]);
    

    output:

    Array
    (
        [0] => value
        [1] => of
        [2] => measured response
        [3] => detect
        [4] => goal
        [5] => method valuation
        [6] => study
    )
    

    The trick here is to use a branch-reset group: (?|...|...). It's just like an alternation contained in a non-capturing group - (?:...|...) - except that within each branch the capturing-group numbers start at the same number. (For more info, see the PCRE docs and search for DUPLICATE SUBPATTERN NUMBERS.)

    Thus, the text we're interested in is always captured group #1. You can retrieve the contents of group #1 for all matches via $matches[1]. (That's assuming the PREG_PATTERN_ORDER flag is set; I didn't specify it like @FailedDev did because it's the default. See the PHP docs for details.)

提交回复
热议问题