Extract words from string with preg_match_all

前端 未结 7 2258
你的背包
你的背包 2020-12-21 17:14

I\'m not good with regex but i want to use it to extract words from a string.

The words i need should have minimum 4 characters and the provided string can

7条回答
  •  离开以前
    2020-12-21 17:48

    You can use the regex below for simple strings. It will match any non-whitespace characters with min length = 4.

    preg_match_all('/(\S{4,})/i', $str, $m);
    

    Now $m[1] contains the array you want.

    Update:

    As Gordon said, the pattern will also match the '(20-40)'. The unwanted numbers can be removed using this regex:

    preg_match_all('/(\pL{4,})/iu', $str, $m);
    

    But I think it only works if PCRE is compiled with UTF-8 support. See PHP PCRE (regex) doesn't support UTF-8?. It works on my computer though.

提交回复
热议问题