爆炸功能不是分解字符

时间:2011-02-25 14:57:20

标签: php string explode

我正在寻找一个explode类型的函数,该函数将按字符分解字符串,但如果字符在字符内,则还要删除字符列表。

例如:

$str = "hello, this is, a test 'some, string' thanks";
explode_func($str, ",", "'");

这会在$str之前爆炸,,但忽略,

中的任何'

预期产出:

Array
(
    [0] => hello
    [1] => this is
    [2] => a test
    [3] => thanks
)

另一个例子是:

$str = "hello, this is, a test (some, string) thanks";
explode_func($str, ",", "()");

这会在$str之前展开,但忽略,(之间的任何)以获得相同的输出。

有什么想法吗?

2 个答案:

答案 0 :(得分:5)

str_getcsv()

$str = "hello, this is, a test 'some, string' thanks";
$array = str_getcsv($str, ",", "'");

应该给出:

Array
(
    [0] => hello
    [1] => this is
    [2] => a test 'some, string' thanks
)

答案 1 :(得分:2)

您最好的选择是首先删除您想要忽略的区域。

function explode($str, $separator, $ignore_pattern) {
    $newStr = preg_replace($ignore_pattern, '', $str);
    return explode($separator, $str);
}

用法:

$str = "hello, this is, a test (some, string) thanks";
$array = explode($str, ',', '/\(.*?\)/');

未经测试,但理论是坚实的