繁体   English   中英

使用 preg_match_all 和正则表达式创建一个单词数组

[英]Create a array of words using preg_match_all and regular expression

我正在使用如下所示的 PHP 函数preg_match_all()创建一个包含多个单词的数组。

// the string which contains the text 
$string = "Lorem ipsum dolor sit amet elit";

// the preg_match_all() function
preg_match_all('/([a-z]*?)(?= )/i', $string, $matches);

// debug array
debug($matches[0]);

// output
[(int) 0 => 'Lorem',
    (int) 1 => '',
    (int) 2 => 'ipsum',
    (int) 3 => '',
    (int) 4 => 'dolor',
    (int) 5 => '',
    (int) 6 => 'sit',
    (int) 7 => '',
    (int) 8 => 'amet',
    (int) 9 => ''
]

但是当我调试或打印包含所有单词的数组时,最后一个单词从数组中删除,在这种情况下它将是单词“elit”。 我怎样才能解决这个问题?

您可以使用(?= |$)作为前瞻,意思是一个单词后跟一个非单词或输入的结尾:

preg_match_all('/([a-z]+)(?=\W|$)/i', $string, $matches);

print_r($matches[0]);

输出:

Array
(
    [0] => Lorem
    [1] => ipsum
    [2] => dolor
    [3] => sit
    [4] => amet
    [5] => consectetur
    [6] => adipiscing
    [7] => elit
    [8] => Lorem
    [9] => ipsum
    [10] => dolor
    [11] => sit
    [12] => amet
    [13] => consectetur
    [14] => adipiscing
    [15] => elit
)

顺便说一句,您可以使用拆分操作获得相同的结果:

$tokens = preg_split('/\h+/', $string);

\\h匹配水平空白。

使用以下正则表达式获取所有单词

\\w匹配任何单词字符(字母、数字、下划线)

preg_match_all('#\w+#', $string, $words);
print_r($words);

会输出

Array
(
    [0] => Array
        (
            [0] => Lorem
            [1] => ipsum
            [2] => dolor
            [3] => sit
            [4] => amet
            [5] => consectetur
            [6] => adipiscing
            [7] => elit
            [8] => Lorem
            [9] => ipsum
            [10] => dolor
            [11] => sit
            [12] => amet
            [13] => consectetur
            [14] => adipiscing
            [15] => elit
        )

)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM