遇到逗号分隔字符串的第 N 个值后将字符串拆分为 2 个字符串

问题描述 投票:0回答:9

所以,我有一个逗号分隔的字符串,我想在计数 x 逗号后将其拆分为两个字符串。

所以,如果我的字符串如下:

临时 1、临时 2、临时 3、临时 4、临时 5、临时 6、临时 7、临时 8、临时 9、临时 10

我想在计数 4 个逗号后将其分成两个字符串,我希望:

$string1 = 'temp1, temp2, temp3, temp4, ';

$string2 = 'temp5, temp6, temp7, temp8, temp9, temp10';

如何在 PHP 中实现这一目标?

php string split
9个回答
3
投票

只是为了好玩。

{4}
可以更改或用变量替换:

preg_match('/([^,]+,){4}/', $string, $matches);

$string1 = $matches[0];
$string2 = str_replace($string1, '', $string);

1
投票

有很多方法可以做到这一点 - 一种方法是爆炸字符串,然后爆炸该数组的切片,如下所示:

$x = 4;
$delim = ', ';
$str = 'temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10';
$parts = explode($delim,$str);
$string1 = implode($delim,array_slice($parts,0,$x)) . $delim;
$string2 = implode($delim,array_slice($parts,$x));

对我来说,这是完成工作最干净、最易读的方式,并且不需要循环。


0
投票

另一种方法是迭代每个字符:

    $string = "temp1, temp2, temp3, temp4, temp5, temp6, temp7";

    $commacount = 0;
    $stringBefore = "";
    $stringAfter = "";
    $splitHasHappened = false;
    foreach (str_split($string) as $char) {

        if ($splitHasHappened) {
            $stringAfter .= $char;
        }
        else {
            $stringBefore .= $char;
        }

        if ($char == ",") {
            $commacount++;
        }

        if ($commacount == 4) {
            $splitHasHappened = true;
        }

    }

    echo "Before: $stringBefore - After $stringAfter"

0
投票

你可以将它分解成一个数组

$array = explode(",",$string);
for($i=0;$i<4;$i++){
  $string1[$i]=$array[$i];
} 
$string1 = implode(",",$string1);
for($i=4;$i<count($array);$i++){
  $string2[$i]=$array[$i];
}
$string2 = implode(",",$string2);

0
投票

您可以创建一个简单的函数,它接受 2 个参数(逗号分隔的字符串和要分割的索引)。结果将是一个带有 2 个键的数字索引数组:0 和 1。 $array[0] 保存第一部分, $array1 保存第二部分。下面是函数:

     <?php

        $strings    = "temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10";


        function splitAtIndex($commaString, $index){
            $arrBlended     = array();
            $arrStrings     = preg_split("#,\s?#", $commaString);
            if(!empty($arrStrings)){
                $partB          = array_splice($arrStrings, $index);
                $partA          = $arrStrings;

                $arrBlended[]   = implode(", ", $partA) . ", ";
                $arrBlended[]   = implode(", ", $partB);

            }
            return $arrBlended;
        }

        $arrSplitStrings        = splitAtIndex($strings, 4);
        $string1                = $arrSplitStrings[0]; //<== 'temp1, temp2, temp3, temp4, '
        $string2                = $arrSplitStrings[1]; //<== 'temp5, temp6, temp7, temp8, temp9, temp10' 
        var_dump($arrSplitStrings);

        // DUMPS 
        array (size=2)
          0 => string 'temp1, temp2, temp3, temp4, ' (length=28)
          1 => string 'temp5, temp6, temp7, temp8, temp9, temp10' (length=41)

测试并确认结果此处


0
投票

我不喜欢为此使用循环。您实际上需要对输入进行一些检查/验证:

<?php

$count = 4;
$str = 'temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10';
$match = preg_match('/^([^,]+,\s?){' . $count . '}/', $str, $matches) ? $matches[0] : false;
if ($match) {
    $position = strlen($match);
    $str1 = substr($str, 0, $position);
    $str2 = substr($str, $position);
}

0
投票

使用

str_word_count
array_slice
array_filter
substr
函数的解决方案:

$str = "temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10";

$comma_number = 4;
// finding the position of 4th comma
$pos = key(array_slice(array_filter(str_word_count($str, 2, ","), function($v){
    return $v == ",";
}), $comma_number - 1, 1, true));

$string1 = substr($str, 0, $pos + 2);
$string2 = substr($str, $pos + 2);

var_dump($string1, $string2);

输出:

string(28) "temp1, temp2, temp3, temp4, "
string(41) "temp5, temp6, temp7, temp8, temp9, temp10"

0
投票

这对我来说非常适合分割特定的逗号分隔计数值并添加 br 标签

<?php 
$string='temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10';
$delim = ',';
$x = 4;
$parts = explode($delim,$string);
$numberofloop=ceil(Count($parts)/$x);
for($i=0,$j=0;$i<$numberofloop;$i++){
        echo implode($delim,array_slice($parts,$j,$x))."<br>";
        $j=$j+$x;   
}
?>

0
投票

没有比

preg_split()
更直接或更合适的工具来完成此任务。

为了确保从本机函数调用返回两个字符串,允许可选的尾随逗号和尾随空格,允许在“前半部分”字符串中匹配少于 N 个值,并将输出元素的数量限制为

2

代码:(演示

$str = 'temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10';
$times = 4;

[$string1, $string2] = preg_split("/(?:[^,]+,? ?){0,$times}\K/", $str, 2);

var_dump($string1, $string2);
// string(28) "temp1, temp2, temp3, temp4, "
// string(41) "temp5, temp6, temp7, temp8, temp9, temp10"

如果要删除第一个返回字符串末尾的尾随逗号和空格,请将 \K 移至可选逗号之前。 (演示)

[$string1, $string2] = preg_split("/(?:[^,]+\K,? ?){0,$times}/", $str, 2);
// string(26) "temp1, temp2, temp3, temp4"
// string(41) "temp5, temp6, temp7, temp8, temp9, temp10"
© www.soinside.com 2019 - 2024. All rights reserved.