Xeen
Xeen

Reputation: 7003

How to split text in 2 halves?

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 . ?

Upvotes: 1

Views: 914

Answers (2)

KodeFor.Me
KodeFor.Me

Reputation: 13511

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.

Upvotes: 0

Andreas
Andreas

Reputation: 23958

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.

Upvotes: 1

Related Questions