如何将文本分成两半?

时间:2016-05-09 08:41:30

标签: php string

我是这样做的:

if(strlen($block_text) > 2000) {
  $half = strlen($block_text)/2;
  $second_half = substr($block_text, $half);
  $block_text = substr($block_text, 0, $half);
}

但问题是$second_half从一个单词的中间开始,$block_text在一个单词的中间结束。是否有可能以某种方式调整它,以便前半部分在点.之后结束?

2 个答案:

答案 0 :(得分:1)

if(strlen($block_text) > 2000) {
  $half = strpos($block_text, ".",  strlen($block_text)/2);
  $second_half = substr($block_text, $half);
  $block_text = substr($block_text, 0, $half);
}

现在它将在文本的一半后找到第一个点。

答案 1 :(得分:0)

我刚试过这个并且似乎对我有用:

if ( 2000 < strlen( $block_text ) ) {
    $string_parts = explode( " ", $block_text );
    $half = join( " ", array_slice( $string_parts, 0, floor( count( $string_parts ) / 2 ) ) );
    $second_half = join( " ", array_slice( $string_parts, floor( count( $string_parts ) / 2 ) ) );
}

除了上面所写的内容之外,为了获得更好的准确性,您可能需要删除字符串中的多个空格字符。