簡體   English   中英

用php逐步拆分字符串

[英]Splitting a string with php incrementally

我有一個想拆分的PHP字符串。 該字符串是來自數據庫的ID號的串聯。

下面是一個字符串示例,但每個ID用“ _”分隔可能會很長:

ID_1_10_11_12

我想將字符串拆分為以下內容:

ID_1_10_11_12

ID_1_10_11

ID_1_10

ID_1

然后將它們連接到一個新的字符串中,該字符串順序顛倒,然后用空格分隔:

新字符串=“ ID_1 ID_1_10 ID_1_10_11 ID_1_10_11_12”

我不知道這個。 我試圖用“ _”將原始值分解成一個數組,但這只剩下數字。

對於我應該如何處理此問題的任何建議,我將不勝感激。 作為參考,這些ID寫入復選框的類值,以便可以將父值和子值分組,然后通過jquery函數進行操作。

可能不是最優雅的方式,如果ID少於2個,它將中斷,但這將返回您要求的字符串:

$str = "ID_1_10_11_12";

//creates an array with all elements
$arr = explode("_", $str);

$new_str = ' ID_' . $arr[1];
for ($i=2; $i<count($arr); $i++)
{
    $tmp =  explode(" ", $new_str);
    $new_str .= " " . $tmp[$i-1] . "_" . $arr[$i];
}
$new_str = trim($new_str);

echo $new_str; //echoes ID_1 ID_1_10 ID_1_10_11 ID_1_10_11_12

我認為它的可用性不高,但是您可以使用。

然后,您可以簡單地explode(" ", $new_str) ,您還將擁有一個包含該字符串中所有元素的數組,您可以按照自己的方式進行explode(" ", $new_str)

顯然,也可以加一個if (count($arr) < 3)之前, for以檢查是否存在后小於2的數組元素ID和退出功能打印$new_str而不與白色空間trim($new_str)如果要輸入少於2個ID數組。

編輯:修剪左空白。

我的測試本地服務器無法進行驗證,但是我相信這可以工作。

<?php
/*

ID_1_10_11_12
ID_1_10_11
ID_1_10
ID_1

ID_1 ID_1_10 ID_1_10_11 ID_1_10_11_12

*/
$str = "ID_1_10_11_12";
$delim = "_";
$spacer = " ";
$ident = "ID";
$out = "";

// make an array of the IDs
$idList = explode($delim, $str);

// loop through the array
for($cur = 0; $cur >= count($idList); $cur++){
    // reset the holder
    $hold = $ident;

    // loop the number of times as the position beyond 0 we're at
    for($pos = -1; $pos > $cur; $pos++){

        // add the current id to the holder
        $hold .= $delim . $idList[$cur]; // "ID_1"
    }

    // add a spacer and the holder to the output if we aren't at the beginning,
    //      otherwise just add the holder
    $out .= ($cur != 0 ? $spacer . $hold : $hold); // "ID_1 ID_1_10"
}
// output the result
echo $out;

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM