题目:有一个字符串,用“。”分割,写一个程序,合并字符串中相同项。如字符串“大家好[81]。你是谁[3]。大家好[3]。老师好[12]。上午好。上午好[12]。”,合并后为“大家好[84]。你是谁[3]。老师好[12]。上午好[13]。”
<?php
header("content-type:text/html;charset=GB2312");
$str = "大家好[81]。你是谁[3]。大家好[3]。老师好[12]。上午好。上午好[12]";
//输出str
print_r($str);
echo "<br>";
//explode() 函数使用一个字符串分割另一个字符串,并返回由字符串组成的数组。这里是以“。”分割
$array = explode("。", $str);
$result = array();
//输出Array数组
foreach ($array as $value){
print_r($value);
echo "\t";
}
echo "<br>";
foreach ($array as $value){
//以“[”分割得到新的数组tmp
$tmp[] = explode("[", $value);
}
$newArray = $tmp;
foreach ($tmp as $k =>$value){
//设置标志位
$flag = 0;
$tmp_cont = $value[0];
//判断是否存在数字,不存在置为1
if(isset($value[1])){
$number = explode("]", $value[1]);
}
else{
$number = "1";
}
//设置新数组下标
$new_k = $k;
foreach ($newArray as $key => &$newArrayValue){
$k ++;
if($k >= 6) break;
//比较数组内容是否相同,相同则数字相加,得到新数组,flag置为1
if($tmp_cont == $newArray[$k][0]){
$flag = 1;
$number_new = explode("]", $newArray[$k][1]);
$number_new[0] += $number[0];
$result[$new_k] = $tmp_cont."[".$number_new[0]."]";
}
}
if($flag == 0 && $new_k < 5){
$result[$new_k] = $tmp_cont."[".$number[0]."]";
}
}
//输出新数组
foreach ($result as $value){
print_r($value);
echo "\t";
}
echo "<br>";
//implode() 函数返回一个由数组元素组合成的字符串。输出新字符串
echo implode("。", $result);
?>