views:

48

answers:

3

I have a string of the form "a-b""c-d""e-f"... Using preg_match, how could I extract them and get an array as:

Array
(
    [0] =>a-b
    [1] =>c-d
    [2] =>e-f
    ...
    [n-times] =>xx-zz
)

Thanks

+3  A: 

You can do:

$str = '"a-b""c-d""e-f"';
if(preg_match_all('/"(.*?)"/',$str,$m)) {
    var_dump($m[1]);
}

Output:

array(3) {
  [0]=>
  string(3) "a-b"
  [1]=>
  string(3) "c-d"
  [2]=>
  string(3) "e-f"
}
codaddict
A: 

Here's my take on it.

$string = '"a-b""c-d""e-f"';

if ( preg_match_all( '/"(.*?)"/', $string, $matches ) )
{
  print_r( $matches[1] );
}

And a breakdown of the pattern

"   // match a double quote
(   // start a capture group
.   // match any character
*   // zero or more times
?   // but do so in an ungreedy fashion
)   // close the captured group
"   // match a double quote

The reason you look in $matches[1] and not $matches[0] is because preg_match_all() returns each captured group in indexes 1-9, whereas the entire pattern match is at index 0. Since we only want the content in the capture group (in this case, the first capture group), we look at $matches[1].

Peter Bailey
+3  A: 

Regexp are not always the fastest solution:

$string = '"a-b""c-d""e-f""g-h""i-j"';
$string = trim($string, '"');
$array = explode('""',$string);
print_r($array);

Array ( [0] => a-b [1] => c-d [2] => e-f [3] => g-h [4] => i-j )
Ben
You could use `trim( $string, '"' )` instead of `substr()` twice.
Peter Bailey
You're right, fixed, thanks.
Ben
Or perhaps `substr( $string, 1, strlen($string)-2 )` to go from the 2nd char to penultimate char.
DisgruntledGoat