문제

I want to implode a string with multiple delimiters. I've already eplode it with this PHP function:

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);

The output of this is:

Array (
   [0] => here is a sample
   [1] =>  this text
   [2] =>  and this will be exploded
   [3] =>  this also 
   [4] =>  this one too 
   [5] => )
)

Can I implode this array with the following multiple delimiters: , . | : ?

Edit:

For define the rules I think this is the best option:

$test = array(':', ',', '.', '|', ':');
$i = 0;
foreach ($exploded as $value) {
    $exploded[$i] .= $test[$i];
    $i++;
}
$test2 = implode($exploded);

The output of $test2 is:

here is a sample: this text, and this will be exploded. this also | this one too :)

I only now need to know how to define the $test array (maybe with preg_match()?) so that it matched these values , . | : and set the variables in a order where it occurs in the string into an array. Is this possible?

도움이 되었습니까?

해결책

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;

The output of this is:

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 :)

You can see it working here.

For more information what's the function of strpbrk in this script, see here.

It's my first contribution to Stack Overflow, hope it helps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top