tags:

views:

57

answers:

3

Basically, I want to enter text into a text area, and then use them. For example

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

I know I could use explode to make each line into an array, and then use a foreach loop to use each line separately, but how would I separate the three variables to use?

+1  A: 

try preg_split http://php.net/manual/en/function.preg-split.php

robertbasic
+3  A: 

Besides preg_split:

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

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

you could do a 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
        )

)
*/
Bart Kiers
+1  A: 

if necessary, you could make several calls to "explode"

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

paullb
The questions was 'how to split' but not 'how many ways to split'.
Andrejs Cainikovs
What a useless comment. Its a valid solution.
paullb
@Andrejs, I agree with @paullb here: the question is how to get the tokens/variables on each line. Iterating over the input line by line and calling `explode(..., explode(...))` is a valid solution, so why not suggest it? I might not have used the word 'useless' however, which has a rather negative sound to it.
Bart Kiers
@paulib. It's *working* solution, not a valid one.
Andrejs Cainikovs
it could be perfectly valid depending on the situation. Please stop arguing for no reason.
paullb
Reason: recursion is evil.
Andrejs Cainikovs