【问题标题】:Which delimiter was used?使用了哪个分隔符?
【发布时间】:2023-09-26 03:20:01
【问题描述】:

我需要用不同的分隔符分割一个字符串。所以我找到并使用了这段代码:

function explodeX($delimiters,$string)
{
    $return_array = Array($string);
    $d_count = 0;
    while (isset($delimiters[$d_count]))
    {
        $new_return_array = Array();
        foreach($return_array as $el_to_split)
        {
            $put_in_new_return_array = explode($delimiters[$d_count],$el_to_split);
            foreach($put_in_new_return_array as $substr)
            {
                $new_return_array[] = $substr;
            }
        }
        $return_array = $new_return_array;
        $d_count++;
    }
    return $return_array;
} 

它工作得很好,但现在,我需要反转它并找到它实际使用的分隔符。 我用了这种线:

$val=explodeX(array("+","-","*","/"), $input);

现在,我需要返回正确的分隔符。

提前致谢。

【问题讨论】:

  • 请举一个$input的例子和预期的输出。

标签: php split explode delimiter


【解决方案1】:

你在$delimiters中设置的所有分隔符都使用了,如下行所示:

while (isset($delimiters[$d_count]))

$d_count 在循环底部递增,$d_count++,并在循环遍历所有分隔符后返回$return_array,与$string 分隔的距离与您指定的一样多。

要将正确的分隔符放回原来的位置,你不能,除非你修改你在$return_array中返回的信息。您正在寻找这样的东西:

$return_array[] = $new_return_array;
$delim = $delimiters[$d_count];
$return_array['delim'] = new Array();
$return_array['delim'][$delim][] = $new_return_array;
$d_count++;

这会将每个分隔符分隔的单词存储在返回结果的delim 索引下的子数组中。那么你需要做的就是将它们内爆回来:

$string2 = '';
foreach ( $return_array as $delim => $word )
{
    // not sure how to reverse your function at this moment, will get back with this part...
}

【讨论】: