0

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
3
  • 2
    explain the string pattern please Commented Mar 11, 2011 at 15:09
  • What kind of logic was/is behind the connection between the keys and the values??? Commented Mar 11, 2011 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) Commented Mar 11, 2011 at 15:16

3 Answers 3

3

preg_match is your friend :)

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

1 Comment

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/…
1

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.

Comments

0

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

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.