如何拆分包含多个分隔符的列表?

时间:2010-06-16 07:33:21

标签: php

基本上,我想在文本区域中输入文本,然后使用它们。例如

variable1:variable2@variable3
variable1:variable2@variable3
variable1:variable2@variable3

我知道我可以使用explode将每一行变成一个数组,然后使用foreach循环分别使用每一行,但是如何将三个变量分开使用呢?

3 个答案:

答案 0 :(得分:4)

除了preg_split

$line = 'variable11:variable12@variable13';
print_r(preg_split('/[:@]/', $line));

/*
Array
(
    [0] => variable11
    [1] => variable12
    [2] => variable13
)
*/

你可以做preg_match_all

$text = 'variable11:variable12@variable13
variable21:variable22@variable23
variable31:variable32@variable33';

preg_match_all('/([^\r\n:]+):([^\r\n@]+)@(.*)\s*/', $text, $matches, PREG_SET_ORDER);

print_r($matches);

/*
Array
(
    [0] => Array
        (
            [0] => variable11:variable12@variable13

            [1] => variable11
            [2] => variable12
            [3] => variable13
        )

    [1] => Array
        (
            [0] => variable21:variable22@variable23

            [1] => variable21
            [2] => variable22
            [3] => variable23
        )

    [2] => Array
        (
            [0] => variable31:variable32@variable33
            [1] => variable31
            [2] => variable32
            [3] => variable33
        )

)
*/

答案 1 :(得分:2)

答案 2 :(得分:1)

如果有必要,你可以多次调用“爆炸”

http://jp.php.net/manual/en/function.explode.php