开发者

extract every occurrence on string

I have a string of the form "a-b""c-d""e-f"... Using preg_match, how could I extra开发者_StackOverflow中文版ct them and get an array as:

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

Thanks


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"
}


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 )


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].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜