Skip to content

Instantly share code, notes, and snippets.

@aaronjorbin
Created January 8, 2017 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronjorbin/48b41494994f7f92a79f07b2098d21a4 to your computer and use it in GitHub Desktop.
Save aaronjorbin/48b41494994f7f92a79f07b2098d21a4 to your computer and use it in GitHub Desktop.
An alternative splitting algorithm for https://github.com/JJJ/publishiza
<?php
/*
Plugin Name: Jorbishiza
*/
add_filter( 'publishiza_format_post_content_for_twitter', 'jorbishiza_format_post_content_for_twitter', 10, 3);
function jorbishiza_format_post_content_for_twitter( $tweets, $text, $length ){
$tweets = array();
$decoded = html_entity_decode( $text, ENT_QUOTES, 'UTF-8' );
$stripped = wp_strip_all_tags( $decoded, true );
// Let's try to split by fragments
$fragments = preg_split( '/(?<=[\!\?,\.]\s)/', $stripped );
$fragmentsRemaining = count( $fragments );
$currentFragment = 0;
$caryover = '';
while( $fragmentsRemaining > 0 ) {
while( empty( trim( $fragments[ $currentFragment ] ) ) ) {
$currentFragment++;
$fragmentsRemaining--;
}
$newTweet = '';
if ( $caryover ) {
$newTweet = $caryover;
$caryover = '';
$potentialFragment = trim( $fragments[ $currentFragment ] );
if ( strlen( $newTweet) + strlen( $potentialFragment ) <= $length ){
$newTweet .= ' ' . $potentialFragment;
$currentFragment++;
$fragmentsRemaining--;
}
} else {
$newTweet = trim( $fragments[ $currentFragment ] );
$fragmentsRemaining--;
$currentFragment++;
}
if ( strlen( $newTweet ) > $length ){
// it's already too long
$split = wordwrap( $newTweet, $length, "\n", false );
$trimmed = array_map( 'trim', explode( "\n", $split ) );
$tmptweets = array_filter( $trimmed );
$caryover = array_pop( $tmptweets );
foreach ($tmptweets as &$value) {
$value = trim( $value . html_entity_decode( '&hellip;', 0, 'UTF-8' ) );
}
unset($value);
$tweets = array_merge( $tweets, $tmptweets );
} else {
$endloop = false;
while ( false === $endloop ){
$potentialFragment = trim( $fragments[ $currentFragment ] );
if ( strlen( $newTweet) + strlen( $potentialFragment ) <= $length ){
$newTweet .= ' ' . $potentialFragment;
$currentFragment++;
$fragmentsRemaining--;
} else {
$endloop = true;
}
}
$tweets[] = trim( $newTweet );
}
}
return $tweets;
}
add_filter( 'publishiza_storm_ellipsis', '__return_false' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment