1

I've done it like so:

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

but the problem here is that the $second_half starts in the middle of a word and the $block_text ends in the middle of a word. Could it be possible to tweak it somehow so that the first half ends after a dot . ?

Xeen
  • 6,955
  • 16
  • 60
  • 111

2 Answers2

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);
}

Now it will find the first dot after half the text.

Xeen
  • 6,955
  • 16
  • 60
  • 111
Andreas
  • 23,610
  • 6
  • 30
  • 62
0

I've just tried this and seems working well for me:

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 ) ) );
}

In addition to what I wrote above, in order to have even better accuracy, you may need to remove multiple space characters found in your string.

Avag Sargsyan
  • 2,437
  • 3
  • 28
  • 41
KodeFor.Me
  • 13,069
  • 27
  • 98
  • 166