3

"a-b""c-d""e-f"... Usingという形式の文字列がありますが、preg_matchそれらを抽出して配列を次のように取得するにはどうすればよいですか。

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

ありがとう

4

3 に答える 3

3

できるよ:

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

出力:

array(3) {
  [0]=>
  string(3) "a-b"
  [1]=>
  string(3) "c-d"
  [2]=>
  string(3) "e-f"
}
于 2010-05-04T16:11:44.247 に答える
3

正規表現は常に最速のソリューションとは限りません:

$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 )
于 2010-05-04T16:14:48.770 に答える
0

これが私の見解です。

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

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

そしてパターンの内訳

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

検索して検索し$matches[1]ない$matches[0]理由preg_match_all()は、キャプチャされた各グループがインデックス 1 ~ 9 で返されるのに対し、パターン マッチ全体はインデックス 0 にあるためです。キャプチャ グループ (この場合は最初のキャプチャ グループ) のコンテンツのみが必要なので、私たちは見ます$matches[1]

于 2010-05-04T16:13:43.480 に答える