我正在开发一个格式化数据的脚本:
如果需要,可以更换它们(你的医生会帮助你):{1:你的椅子|你的枕头| {I:你的椅子1 |你的枕头2 |你的床垫3 |你的鞋子4} |你的鞋子}和我希望{}内的所有内容都成为新的列表,其中包含在大括号{a:}
中指定的类型首选分隔符是|
PHP代码:
function processforsublist($str)
{
$start = strpos($str, '{');
$format = substr($str, $start+1 , 1);
$end = strpos($str, '}');
if($start!==false && $end!==false)
{
$cut = substr($str, $start, ($end-$start)+1);
$class = '';
switch ($format) {
case '1':
$class = 'list_number';
break;
case 'a':
$class = 'list_alpha_small';
break;
case 'A':
$class = 'list_alpha_caps';
break;
case 'i':
$class = 'list_roman_small';
break;
case 'I':
$class = 'list_roman_caps';
break;
default:
$class = 'list_number';
break;
}
$cutn = str_replace('{', '', $cut);
$cutn = str_replace('}', '', $cutn);
$cutn = str_replace($format.":", '', $cutn);
//echo $cutn;
$exploded = explode('|', $cutn);
$lis = '';
foreach ($exploded as $value) {
if(strpos($str, '{')!==false)
$lis .= "<li>".processforsublist($value)."</li>";
else
$lis .= "<li>".trim($value)."</li>";
}
$newstr = "<ol class='$class'>$lis</ol>";
echo $str."<hr/>".$cut."<hr/>".$newstr."<hr/>";
$istr = str_replace($cut, $newstr, $str);
return $istr;
}
else {
return $str;
}
}
echo processforsublist('Change them if needed (your doctor will help you with this):{1:Your chair|Your pillow|{I:Your chair 1|Your pillow 2|Your mattress 3|Your shoes 4}|Your shoes}');
当前输出:
Change them if needed (your doctor will help you with this):
1.Your chair
2.Your pillow
3.Your chair 1
4.Your pillow 2
5.Your mattress 3
6.Your shoes 4
|Your shoes}
必需输出:
Change them if needed (your doctor will help you with this):
1.Your chair
2.Your pillow
I.Your chair 1
II.Your pillow 2
III.Your mattress 3
IV.Your shoes 4
3.Your shoes
答案 0 :(得分:1)
$str="{1:Your chair|Your pillow|{I:Your chair 1|Your pillow 2|Your mattress 3|Your shoes 4}|Your shoes}";
$str=str_replace("{1:","<ol type=1><li>",$str);
$str=str_replace("{a:","<ol type=a><li>",$str);
$str=str_replace("{A:","<ol type=A><li>",$str);
$str=str_replace("{i:","<ol type=i><li>",$str);
$str=str_replace("{I:","<ol type=I><li>",$str);
$str=str_replace("}","</li></ol>",$str);
$str=str_replace("|","</li><li>",$str);
答案 1 :(得分:0)
根据您的描述,听起来JSON字符串可能是更好的选择。查看json_encode
和json_decode
。它会让你的生活好一百万倍。
答案 2 :(得分:0)
我认为你需要改变一些事情。 这里只是一个简短的要点:
尝试$end = strrpos($str, '}');
代替$end = strpos($str, '}');
,就像它搜索第一次出现的当前代码一样}所以你拥有的字符串将作为第一次出现{和第一次出现这是错误的,因为它之间会有任意数量的'{'。
$cutn = str_replace('{', '', $cut);
$cutn = str_replace('}', '', $cutn);
这将取代所有出现次数
尝试$cutn = preg_replace('/{/', '', $cut,1);
$cutn =substr_replace($cutn,'', strrpos($cutn, '}'), 1);
$exploded = explode('|', $cutn);
这将为您提供所有内容的数组,但不包含子数组,因为您需要它来显示罗马数字。所以你需要改变它。希望这有帮助