up vote 0 down vote favorite
share [fb]

I have a string that looks like:

'- 10 TEST (FOO 3 TEST.BAR 213 BAZ (\HELLO) TEST'

Same format for any other string. How could I get, the value of FOO, BAR and BAZ. So, for instance, I can get an array as:

'FOO' => 3,
'BAR' => 213,
'BAZ' => HELLO
link|improve this question
2  
explain the string pattern please – amosrivera Mar 11 at 15:09
What kind of logic was/is behind the connection between the keys and the values??? – powtac Mar 11 at 15:09
pattern is basically as: (CONST value X.CONST value CONST (\VALUE) X...), where CONST is the placer hoder in this case (never change) – CalebW Mar 11 at 15:16
feedback

3 Answers

up vote 0 down vote accepted

Assuming neither the constants nor the values have space in them, this will work for the given example :

$str = '(CONST1 value1 X.CONST2 value2 CONST3 (\VALUE3) X...)';
preg_match('/\((\S+)\s+(\S+)\s+.*?\.(\S+)\s+(\S+)\s+(\S+)\s+\(\\\\(\S+)\)/', $str, $m);
$arr = array();
for($i=1; $i<count($m);$i+=2) {
  $arr[$m[$i]] = $m[$i+1];
}
print_r($arr);

output:

Array
(
    [CONST1] => value1
    [CONST2] => value2
    [CONST3] => VALUE3
)

explanation

\(          : an open parenthesis
(\S+)       : 1rst group, CONST1, all chars that are not spaces
\s+         : 1 or more spaces
(\S+)       : 2nd group, value1
\s+.*?\.    : some spaces plus any chars plus a dot
(\S+)       : 3rd group, CONST2
\s+         : 1 or more spaces
(\S+)       : 4th group, value2
\s+         : 1 or more spaces
(\S+)       : 5th group, CONST3
\s+         : 1 or more spaces
\(          : an open parenthesis
\\\\        : backslash
(\S+)       : 6th group, VALUE3
\)          : a closing parenthesis
link|improve this answer
perfect, thanks! – CalebW Mar 11 at 16:06
You're welcome. – M42 Mar 11 at 16:08
feedback

You want to use preg_match to first grab the matches and then put them into an array. This will give you what you are looking for:

$str = '- 10 TEST (FOO 3 TEST.BAR 213 BAZ (\HELLO) TEST';

preg_match('/FOO (\d+).+BAR (\d+).+BAZ \(\\\\(\w+)\)/i', $str, $match);

$array = array(
    'FOO' => $match[1],
    'BAR' => $match[2],
    'BAZ' => $match[3]
);

print_r($array);

This is assuming though that the first two values are numbers and the last is word characters.

link|improve this answer
feedback

preg_match is your friend :)

link|improve this answer
I think this answer is a bit too vague (as is the question). In lieu of a specific advise, here are some tools that might help OP with his issue: stackoverflow.com/questions/89718/… – mario Mar 11 at 15:19
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.