1

I have a string:

$a = "Name[value]";

How do I get the 'Name' and 'value' portions of string into variables from this string? I'm not that great at regular expressions. Thanks!

mu is too short
  • 426,620
  • 70
  • 833
  • 800
orourkedd
  • 6,201
  • 5
  • 43
  • 66

3 Answers3

10

so this should do the trick for you:

(.*)\[(.*)\]

This is the PHP syntax:

<?php
$subject = "Name[value]";
$pattern = '/(.*)\[(.*)\]/';
preg_match($pattern, $subject, $matches);
print_r($matches);
?>

Output:

Array
(
    [0] => Name[value]
    [1] => Name
    [2] => value
)

Enjoy.

Johannes Fahrenkrug
  • 42,912
  • 19
  • 126
  • 165
1
<?php

/**
 * Regex Quick Extraction - ignore $matches[0];
 */

$a = "Name[value]";

preg_match('/([^\]]*)\[([^\]]*)\]/',$a,$matches);

if(count($matches) > 0) {
    print_r($matches);
}

?>
MyStream
  • 2,533
  • 1
  • 16
  • 33
1

Try this:

 <?php
$a = "Name[value]";
preg_match('/(?<name>.*?)\[(?<value>.*[^\]]+)/', $a, $matched); 
 echo '<pre>'; 
 print_r($matched);
?>

output:

Array
(
    [0] => Name[value
    [name] => Name
    [1] => Name
    [value] => value
    [2] => value
)
The Mask
  • 17,007
  • 37
  • 111
  • 185