我有一个问题,我有一个字符串数组,我想在不同的分隔符爆炸.例如
$example = 'Appel @ Ratte';
$example2 = 'apple vs ratte'
Run Code Online (Sandbox Code Playgroud)
我需要一个在@或vs.中爆炸的阵列
我已经写了一个解决方案,但如果每个人都有更好的解决方案,请在这里发布.
private function multiExplode($delimiters,$string) {
$ary = explode($delimiters[0],$string);
array_shift($delimiters);
if($delimiters != NULL) {
if(count($ary) <2)
$ary = $this->multiExplode($delimiters, $string);
}
return $ary;
}
Run Code Online (Sandbox Code Playgroud)
Ser*_*geS 263
怎么样使用
$output = preg_split( "/ (@|vs) /", $input );
Joh*_*ger 60
你可以把第一个字符串,替换所有@
与vs
使用str_replace
,然后发生爆炸vs
,反之亦然.
par*_*2eu 40
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);
//And output will be like this:
// Array
// (
// [0] => here is a sample
// [1] => this text
// [2] => and this will be exploded
// [3] => this also
// [4] => this one too
// [5] => )
// )
Run Code Online (Sandbox Code Playgroud)
资料来源:php.net上的php @ metehanarslan
小智 11
如何使用strtr()
第一个替换所有其他分隔符?
private function multiExplode($delimiters,$string) {
return explode(
$delimiters[0],
strtr(
$string,
array_combine(
array_slice( $delimiters, 1 ),
array_fill(
0,
count($delimiters)-1,
array_shift($delimiters)
)
)
)
);
}
Run Code Online (Sandbox Code Playgroud)
我想,这有点难以理解,但我测试它在这里工作.
单线ftw!
你可以试试这个解决方案......效果很好
function explodeX( $delimiters, $string )
{
return explode( chr( 1 ), str_replace( $delimiters, chr( 1 ), $string ) );
}
$list = 'Thing 1&Thing 2,Thing 3|Thing 4';
$exploded = explodeX( array('&', ',', '|' ), $list );
echo '<pre>';
print_r($exploded);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)
来源:http : //www.phpdevtips.com/2011/07/exploding-a-string-using-multiple-delimiters-using-php/
您只需使用以下代码:
$arr=explode('sep1',str_replace(array('sep2','sep3','sep4'),'sep1',$mystring));
Run Code Online (Sandbox Code Playgroud)