3

これを行う方法について(これを重複としてフラグを立てる前に)多く見てきましたが、何らかの理由で私の出力が機能していません:

// $delimiters wanted: ', ' | '; ' | ',' | ';' | ' , ' | ', and ' | ' and ' | ',and '
$str = 'Name 1, Name 2; Name 3;Name4 , Name 5,Name 6, and Name 7,and Name 8 and Name 9';
$delimiter = array(
    ', ',
    '; ',
    ';',
    ',',
    ' , ',
    ', and ',
    ' and ',
    ',and '
);
$str_new = explode( $delimiter[0], str_replace($delimiter, $delimiter[0], $str) );

ただし、配列を出力すると、次のようになります。

<?php foreach($str_new as $new) { echo 'a' . $new; } ?>

Array (
    [0] => Name 1
    [1] => Name 2
    [2] => Name 3
    [3] =>        // WHY IS THIS EMPTY?
    [4] => Name 4
    ...
)

リストした区切り文字に一致させるより良い方法はありますか?

4

4 に答える 4

5

あなたの場合、次のように正規表現を使用します。

preg_split('/,? ?and | ?[,;] ?/', $str)

\s他のスペース文字が表示される可能性がある場合 (たとえば、TAB など)、または複数のスペースのケースをカバーする\s*代わりに、スペースを置き換えることもできます。?

于 2013-04-28T08:51:46.937 に答える
1

php.netからこのようなことを試しましたか?

<?php

//$delimiters has to be array
//$string has to be array

function multiexplode ($delimiters,$string) {

    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}

$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
$exploded = multiexplode(array(",",".","|",":"),$text);

print_r($exploded);
?>

または、PHP の複数の区切り文字による文字列の分割のようなもの

于 2013-04-28T08:41:56.730 に答える
0

あなたのコードでは、 の間Name 6, and Name 7で、最初に,が置き換えられ、次にand.

したがって、次の文字列になります。

名前 1、名前 2、名前 3、名前 4、名前 5、名前 6、名前 7、名前 8、名前 9

したがって、空の値...

出力する前に結果の配列をきれいにしてください。

$str_out = array_filter($str_new);
于 2013-04-28T08:52:26.810 に答える