[英]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.