0

I have the following string:

         Apples Bananas Oranges
Me       1      2       3  
Brother  4      4       5

I need a regular expression to get number of apples, bananas and oranges each of us "me and my brother" has.

please help me, I'm totally clueless here.

5
  • 2
    Is this homework? Because you should never be doing this IRL. Commented May 15, 2012 at 21:40
  • Are Me and Brother hard-coded, or are you looking for a more general solution? Commented May 15, 2012 at 21:40
  • anything missing from string? like html table markup? tabs? Commented May 15, 2012 at 21:43
  • this is not a homework thats for sure, the real string values is different from this, but I added that for fun factor. no @dragon there is no markup on this table, its just a chunk of a bigger string Commented May 15, 2012 at 21:51
  • The only way a regular expression (or any simple parser) is going to work is if your data is in some consistent format .. is it? Or is creating code to parse only the provided example sufficient? Commented May 15, 2012 at 21:54

2 Answers 2

2

You probably want some code like this:

$string = file('input.txt');
$headers = array();
$results = array();
foreach($string as $i => $line) {
    preg_match_all('@(\w+)@', $line, $matches);
    if (!$i) {
        $headers = $matches[0];
    } else {
        $name = array_shift($matches[0]);
        $results[$name] = array_combine($headers, $matches[0]);
    }   
}   
print_r($results);

which would result in:

Array
(   
    [Me] => Array
        (   
            [Apples] => 1
            [Bananas] => 2
            [Oranges] => 3
        )   

    [Brother] => Array
        (   
            [Apples] => 4
            [Bananas] => 4
            [Oranges] => 5
        )   

)   
Sign up to request clarification or add additional context in comments.

2 Comments

great, it works if the text was inside of a file, but i cant do that. it has to be a string.
well, that's a trivial change which I'll leave for you saadlulu ;)
0

Roughly

$regexp = "/([\w]+) +([\d]+) +([\d]+) +([\d]+)/";
$matches = array();
preg_match($regexp, $yourDataSet, $matches);

Depending on if you are using 1 long string or a string with newlines you can add \n before the last / in the regexp and make it more precise.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.