php - 在特定事件发生后按特殊字符分割字符串

时间:2015-04-22 07:40:29

标签: php string

我想在每3 .

之后打破一句话

示例字符串:

$var = "ABC.ABC.ABC.ABC.ABC.ABC.ABC.ABC.";

预期结果:

[0] = ABC. ABC. ABC

[1] = ABC. ABC. ABC

[2] = ABC. ABC.

3 个答案:

答案 0 :(得分:3)

您需要使用explode()功能,然后将它们重新添加。像这样:

$line = "ABC.ABC.ABC.ABC.ABC.ABC.ABC.ABC.";
$tempSplit = explode(".", $line);

$result;
for ($x = 0; $x < count($tempSplit); $x++)
{
    $result[intval($x / 3)] .= $tempSplit[$x] . ".";
}

然后,您必须弄清楚您是否希望保留最终.。您可以使用substr()功能删除它:link

答案 1 :(得分:3)

试试这个

var = "ABC.ABC.ABC.ABC.ABC.ABC.ABC.ABC.";
$array=explode(".", $var);
$str="";
$count=0;
$arr="";
for($i=0;$i<sizeof($array);$i++){
    $str[]=$array[$i];

    $count++;
    if($count>2){
        $arr[$i]=implode(". ",$str);
        $str="";
        $count=0;

    }

}
var_dump(array_values($arr));

输出

 array (size=3)
  0 => string 'ABC. ABC. ABC' (length=13)
  1 => string 'ABC. ABC. ABC' (length=13)
  2 => string 'ABC. ABC. ' (length=10)

答案 2 :(得分:2)

您可能想尝试一下:

$test = "ABC.ABC.ABC.ABC.ABC.ABC.ABC.ABC.\n"
      . "The quick brown fox jumps over the lazy dog.\n"
      . "Lorem ipsizzle dolizzle you son of a bizzle amizzle, \n"
      . "its fo rizzle adipiscing elit. The bizzle tellivizzle \n"
      . "velizzle, gizzle volutpizzle, suscipizzle bow wow wow, \n"
      . "owned vizzle, owned. Pellentesque bow wow wow tortor. \n"
      . "Sizzle erizzle. Shizznit izzle dolor dapibus get down \n"
      . "get down tempizzle yo. Maurizzle go to hizzle bizzle \n"
      . "izzle. Da bomb izzle dawg. Pellentesque eleifend \n"
      . "rhoncus dope. In sure break yo neck, yall shiz \n"
      . "dictumst. Shiznit dapibus. Curabitizzle boom \n"
      . "shackalack fo shizzle mah nizzle fo rizzle, mah \n"
      . "home g-dizzle, pretizzle rizzle, mattizzle crackalackin, \n"
      . "eleifend funky fresh, nunc. Shit suscipizzle. Integizzle \n"
      . "sempizzle velit sed daahng dawg.";

$result = preg_split("%((?:[^\.]*?\.){3})%s", $test, -1,
          PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);

echo "<pre>"; print_r ($result); echo "</pre>";

如果它真的与句子有关,它们通常以句号(“。”)结束,后跟空格(“”)。要在结果中避免这些空格,可以使用以下正则表达式:

$result = preg_split("%((?:[^\.]*?\.\s?){3})%s", $test, -1,
          PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);