Automatically split WordPress post content in to 3 columns? - php

I'm currently using the following code from this tutorial to automatically split the WordPress post content in to 2 columns. However, how would I change this code to output 3 columns instead of only 2?
functions.php code:
function content_split($text, $separator = '<hr/>', $start = false ) {
if ( $start === false) {
$start = strlen($text) / 2;
}
$lastSpace = false;
$split = substr($text, 0, $start - 1);
// if the text is split at a good breaking point already.
if (in_array(substr($text, $start - 1, 1), array(' ', '.', '!', '?'))) {
$split .= substr($text, $start, 1);
// Calculate when we should start the split
$trueStart = strlen($split);
// find a good point to break the text.
} else {
$split = substr($split, 0, $start - strlen($separator));
$lastSpace = strrpos($split, ' ');
if ($lastSpace !== false) {
$split = substr($split, 0, $lastSpace);
}
if (in_array(substr($split, -1, 1), array(','))) {
$split = substr($split, 0, -1);
}
// Calculate when we should start the split
$trueStart = strlen($split);
}
//now we know when to split the text
return substr_replace($text, $separator, $trueStart, 0);
}
index.php code:
<div class="first-column my-column">
<?php $text = get_the_content(); $separator = '</div><div class="second-column my-column">'; echo apply_filters('the_content', content_split($text,$separator)); ?>
</div>

function content_split($text, $separator = '<hr/>') {
$string = '';
$start = ceil(strlen($text) / 3);
$string.= substr($text,0,$start);
$string.= $separator;
$string.= substr($text,$start,$start);
$string.= $separator;
$string.= substr($text,($start*2),$start);
return $string;
}

Related

PHP: How can I cut the word and add "..."

How can I cut the words and add "..." after reaching 4 or 5 words?
The code below states I did the character-based word cuttingb but I need it now to be by word.
Currently I have this kind of code:
if(strlen($post->post_title) > 35 )
{
$titlep = substr($post->post_title, 0, 35).'...';
}
else
{
$titlep = $post->post_title;
}
and this is the output of title:
if ( $params['show_title'] === 'true' ) {
$title = '<h3 class="wp-posts-carousel-title">';
$title.= '' . $titlep . '';
$title.= '</h3>';
}
Typically, I'll explode the body and pull out the first x characters.
$split = explode(' ', $string);
$new = array_slice ( $split, 0 ,5);
$newstring = implode( ' ', $new) . '...';
Just know, this method is slow.
Variant #1
function crop_str_word($text, $max_words = 50, $sep = ' ')
{
$words = split($sep, $text);
if ( count($words) > $max_words )
{
$text = join($sep, array_slice($words, 0, $max_words));
$text .=' ...';
}
return $text;
}
Variant #2
function crop_str_word($text, $max_words, $append = ' …')
{
$max_words = $max_words+1;
$words = explode(' ', $text, $max_words);
array_pop($words);
$text = implode(' ', $words) . $append;
return $text;
}
Variant #3
function crop_str_word($text, $max_words)
{
$words = explode(' ',$text);
if(count($words) > $max_words && $max_words > 0)
{
$text = implode(' ',array_slice($words, 0, $max_words)).'...';
}
return $text;
}
via
You should use str_replace function of PHP.
str_replace('your word', '...', $variable);
read that article: http://php.net/manual/en/function.str-replace.php
In WordPress this functionality is done by wp_trim_words() function.
<?php
if(strlen($post->post_title) > 35 )
{
$titlep = wp_trim_words( $post->post_title, 35, '...' );
}
else
{
$titlep = $post->post_title;
}
?>
If you do this functionality using PHP then write code as below:
<?php
$titlep = strlen($post->post_title) > 35 ? substr($post->post_title, 0, 35).'...' : $post->post_title;
?>

Limit WP excerpt to second sentence

I'm using this function to limit my WP excerpt to a sentence instead of just cutting it off after a number of words.
add_filter('get_the_excerpt', 'end_with_sentence');
function end_with_sentence($excerpt) {
$allowed_end = array('.', '!', '?', '...');
$exc = explode( ' ', $excerpt );
$found = false;
$last = '';
while ( ! $found && ! empty($exc) ) {
$last = array_pop($exc);
$end = strrev( $last );
$found = in_array( $end{0}, $allowed_end );
}
return (! empty($exc)) ? $excerpt : rtrim(implode(' ', $exc) . ' ' .$last);
}
Works like a charm, but I would like to limit this to two sentences. Anyone have an idea how to do this?
Your code didn't work for me for 1 sentence, but hey it's 2am here maybe I missed something. I wrote this from scratch:
add_filter('get_the_excerpt', 'end_with_sentence');
function end_with_sentence( $excerpt ) {
$allowed_ends = array('.', '!', '?', '...');
$number_sentences = 2;
$excerpt_chunk = $excerpt;
for($i = 0; $i < $number_sentences; $i++){
$lowest_sentence_end[$i] = 100000000000000000;
foreach( $allowed_ends as $allowed_end)
{
$sentence_end = strpos( $excerpt_chunk, $allowed_end);
if($sentence_end !== false && $sentence_end < $lowest_sentence_end[$i]){
$lowest_sentence_end[$i] = $sentence_end + strlen( $allowed_end );
}
$sentence_end = false;
}
$sentences[$i] = substr( $excerpt_chunk, 0, $lowest_sentence_end[$i]);
$excerpt_chunk = substr( $excerpt_chunk, $lowest_sentence_end[$i]);
}
return implode('', $sentences);
}
I see complexities in your sample code that make it (maybe) harder than it needs to be.
Regular expressions are awesome. If you want to modify this one, I'd recommend using this tool: https://regex101.com/
Here we're going to use preg_split()
function end_with_sentence( $excerpt, $number = 2 ) {
$sentences = preg_split( "/(\.|\!|\?|\...)/", $excerpt, NULL, PREG_SPLIT_DELIM_CAPTURE);
var_dump($sentences);
if (count($sentences) < $number) {
return $excerpt;
}
return implode('', array_slice($sentences, 0, ($number * 2)));
}
Usage
$excerpt = 'Sentence. Sentence! Sentence? Sentence';
echo end_with_sentence($excerpt); // "Sentence. Sentence!"
echo end_with_sentence($excerpt, 1); // "Sentence."
echo end_with_sentence($excerpt, 3); // "Sentence. Sentence! Sentence?"
echo end_with_sentence($excerpt, 4); // "Sentence. Sentence! Sentence? Sentence"
echo end_with_sentence($excerpt, 10); // "Sentence. Sentence! Sentence? Sentence"

How to insert word-wrap function to auto-break a long word in PHP?

How can I insert word-wrap function so that any word that is too long doesn't cut <div> border but line-returns itself?
The following is the variable I want to word-wrap
$body = nl2br(addslashes($_POST['body']));
try out these links:
Smarter word-wrap in PHP for long words?
http://php.net/manual/en/function.wordwrap.php
http://www.w3schools.com/php/func_string_wordwrap.asp
And a custom Function:
function smart_wordwrap($string, $width = 75, $break = "\n") {
// split on problem words over the line length
$pattern = sprintf('/([^ ]{%d,})/', $width);
$output = '';
$words = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
foreach ($words as $word) {
if (false !== strpos($word, ' ')) {
// normal behaviour, rebuild the string
$output .= $word;
} else {
// work out how many characters would be on the current line
$wrapped = explode($break, wordwrap($output, $width, $break));
$count = $width - (strlen(end($wrapped)) % $width);
// fill the current line and add a break
$output .= substr($word, 0, $count) . $break;
// wrap any remaining characters from the problem word
$output .= wordwrap(substr($word, $count), $width, $break, true);
}
}
// wrap the final output
return wordwrap($output, $width, $break);
}
$string = 'hello! toolongheretoolonghereooheeeeeeeeeeeeeereisaverylongword but these words are shorterrrrrrrrrrrrrrrrrrrr';
echo smart_wordwrap($string, 11) . "\n";

Crop the string only after closing tag

I want to cut the string, if the string length is greater than 80.My need is if the string contain tag and cut the string in between the opening and closing tag,string crop should be only after closing tag.THis is my code.
<?php
echo $word='hello good morning<span class="em emj2"></span> <span class="em emj13"></span> <span class="em emj19"></span> <span class="em emj13"></span> hai';
$a=strlen($word);
if($a>80)
{
echo substr($word,0,80);
}
else
echo $word;
?>
I know that my answer is not in good ethics as according to stackoverflow, as I dont have time to explain exactly how every part of it works. But this is a function I use to crop strings and maintain the HTML code.
function truncate($text, $length, $suffix = '…', $isHTML = true) {
$i = 0;
$simpleTags=array('br'=>true,'hr'=>true,'input'=>true,'image'=>true,'link'=>true,'meta'=>true);
$tags = array();
if($isHTML){
preg_match_all('/<[^>]+>([^<]*)/', $text, $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
foreach($m as $o){
if($o[0][1] - $i >= $length)
break;
$t = substr(strtok($o[0][0], " \t\n\r\0\x0B>"), 1);
if($t[0] != '/' && (!isset($simpleTags[$t])))
$tags[] = $t;
elseif(end($tags) == substr($t, 1))
array_pop($tags);
$i += $o[1][1] - $o[0][1];
}
}
$output = substr($text, 0, $length = min(strlen($text), $length + $i));
$output2 = (count($tags = array_reverse($tags)) ? '</' . implode('></', $tags) . '>' : '');
$pos = (int)end(end(preg_split('/<.*>| /', $output, -1, PREG_SPLIT_OFFSET_CAPTURE)));
$output.=$output2;
$one = substr($output, 0, $pos);
$two = substr($output, $pos, (strlen($output) - $pos));
preg_match_all('/<(.*?)>/s', $two, $tags);
if (strlen($text) > $length) { $one .= $suffix; }
$output = $one . implode($tags[0]);
$output = str_replace('</!-->','',$output);
return $output;
}
Then simply do like so:
truncate($your_string, '80', $suffix = '…', $isHTML = true);

Making sure PHP substr finishes on a word not a character

I know how to use the substr function but this will happy end a string halfway through a word. I want the string to end at the end of a word how would I go about doing this? Would it involve regular expression? Any help very much appreciated.
This is what I have so far. Just the SubStr...
echo substr("$body",0,260);
Cheers
substr($body, 0, strpos($body, ' ', 260))
It could be done with a regex, something like this will get up to 260 characters from the start of string up to a word boundary:
$line=$body;
if (preg_match('/^.{1,260}\b/s', $body, $match))
{
$line=$match[0];
}
Alternatively, you could maybe use the wordwrap function to break your $body into lines, then just extract the first line.
You can try this:
$s = substr($string, 0, 261);
$result = substr($s, 0, strrpos($s, ' '));
You could do this: Find the first space from the 260th character on and use that as the crop mark:
$pos = strpos($body, ' ', 260);
if ($pos !== false) {
echo substr($body, 0, $pos);
}
wordwrap and explode then first array element is you want
$wr=wordwrap($text,20,':');
$strs=explode(":",$wr);
$strs[0]
I use this solution:
$maxlength = 50;
substr($name, 0, ($spos = strpos($name, ' ', $lcount = count($name) > $maxlength ? $lcount : $maxlength)) ? $spos : $lcount );
Or inline:
substr($name, 0, ($spos = strpos($name, ' ', $lcount = count($name) > 50 ? $lcount : 50)) ? $spos : $lcount );
function substr_word($body,$maxlength){
if (strlen($body)<$maxlength) return $body;
$body = substr($body, 0, $maxlength);
$rpos = strrpos($body,' ');
if ($rpos>0) $body = substr($body, 0, $rpos);
return $body;
}
What about this?
/**
* #param string $text
* #param int $limit
* #return string
*/
public function extractUncutPhrase($text, $limit)
{
$delimiters = [',',' '];
$marks = ['!','?','.'];
$phrase = substr($text, 0, $limit);
$nextSymbol = substr($text, $limit, 1);
// Equal to original
if ($phrase == $text) {
return $phrase;
}
// If ends with delimiter
if (in_array($nextSymbol, $delimiters)) {
return $phrase;
}
// If ends with mark
if (in_array($nextSymbol, $marks)) {
return $phrase.$nextSymbol;
}
$parts = explode(' ', $phrase);
array_pop($parts);
return implode(' ', $parts); // Additioanally you may add ' ...' here.
}
Tests:
public function testExtractUncutPhrase()
{
$stringUtils = new StringUtils();
$text = 'infant ton-gue could make of both names nothing';
$phrase = 'infant';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 11));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 12));
$text = 'infant tongue5';
$phrase = 'infant';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 11));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 7));
}
public function testExtractUncutPhraseEndsWithDelimiter()
{
$stringUtils = new StringUtils();
$text = 'infant tongue ';
$phrase = 'infant tongue';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
$text = 'infant tongue,';
$phrase = 'infant tongue';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
}
public function testExtractUncutPhraseIsSentence()
{
$stringUtils = new StringUtils();
$text = 'infant tongue!';
$phrase = 'infant tongue!';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 14));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 100));
$text = 'infant tongue!';
$phrase = 'infant tongue!';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
$text = 'infant tongue.';
$phrase = 'infant tongue.';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
}
$pos = strpos($body, $wordfind);
echo substr($body,0, (($pos)?$pos:260));
public function Strip_text($data, $size, $lastString = ""){
$data = strip_tags($data);
if(mb_strlen($data, 'utf-8') > $size){
$result = mb_substr($data,0,mb_strpos($data,' ',$size,'utf-8'),'utf-8');
if(mb_strlen($result, 'utf-8') <= 0){
$result = mb_substr($data,0,$size,'utf-8');
$result = mb_substr($result, 0, mb_strrpos($result, ' ','utf-8'),'utf-8');;
}
if(strlen($lastString) > 0) {
$result .= $lastString;
}
}else{
$result = $data;
}
return $result;
}
Pass the string into funtion Strip_text("Long text with html tag or without html tag", 15)
Then this function will return the first 15 character from the html string without html tags. When string less than 15 character then return the full string other wise it will return the 15 character with $lastString parameter string.
Example:
Strip_text("<p>vijayDhanasekaran</p>", 5)
Result: vijay
Strip_text("<h1>vijayDhanasekaran<h1>",5,"***....")
Result: vijay***....
Try This Function..
<?php
/**
* trims text to a space then adds ellipses if desired
* #param string $input text to trim
* #param int $length in characters to trim to
* #param bool $ellipses if ellipses (...) are to be added
* #param bool $strip_html if html tags are to be stripped
* #param bool $strip_style if css style are to be stripped
* #return string
*/
function trim_text($input, $length, $ellipses = true, $strip_tag = true,$strip_style = true) {
//strip tags, if desired
if ($strip_tag) {
$input = strip_tags($input);
}
//strip tags, if desired
if ($strip_style) {
$input = preg_replace('/(<[^>]+) style=".*?"/i', '$1',$input);
}
if($length=='full')
{
$trimmed_text=$input;
}
else
{
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
$trimmed_text = substr($input, 0, $last_space);
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
}
return $trimmed_text;
}
?>

Categories