我想内打一个包含多个分隔符的字符串。我已经使用这个PHP函数对它进行了内爆:
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);
这个输出是:
Array (
[0] => here is a sample
[1] => this text
[2] => and this will be exploded
[3] => this also
[4] => this one too
[5] => )
)
我是否可以使用以下多个分隔符破坏此数组:,
.
|
:
?
修改
为了定义规则,我认为这是最好的选择:
$test = array(':', ',', '.', '|', ':');
$i = 0;
foreach ($exploded as $value) {
$exploded[$i] .= $test[$i];
$i++;
}
$test2 = implode($exploded);
$test2
的输出是:
here is a sample: this text, and this will be exploded. this also | this one too :)
我现在只需要知道如何定义$test
数组(可能与preg_match()
?),以便它匹配这些值,
.
|
:
并将变量按字符串中的顺序设置为数组。这可能吗?
答案 0 :(得分:2)
function multiexplode ($delimiters,$string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
$string = "here is a sample: this text, and this will be exploded. this also | this one too :)";
echo "Input:".PHP_EOL.$string;
$needle = array(",",".","|",":");
$split = multiexplode($needle, $string);
$chars = implode($needle);
$found = array();
while (false !== $search = strpbrk($string, $chars)) {
$found[] = $search[0];
$string = substr($search, 1);
}
echo PHP_EOL.PHP_EOL."Found needle:".PHP_EOL.PHP_EOL;
print_r($found);
$i = 0;
foreach ($split as $value) {
$split[$i] .= $found[$i];
$i++;
}
$output = implode($split);
echo PHP_EOL."Output:".PHP_EOL.$output;
这个输出是:
Input:
here is a sample: this text, and this will be exploded. this also | this one too :)
Found needle:
Array
(
[0] => :
[1] => ,
[2] => .
[3] => |
[4] => :
)
Output:
here is a sample: this text, and this will be exploded. this also | this one too :)
您可以看到它正常工作here。
有关此脚本中strpbrk
的功能的更多信息,请参阅here。
这是我对Stack Overflow的第一次贡献,希望它有所帮助。