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;
?>
Related
I am trying to extract relative keywords from description input which use Wysiwyg, with multi language english/arabic… using the following function but its not doing the task I want. Have a look the function I am using:
function extractKeyWords($string) {
mb_internal_encoding('UTF-8');
$stopwords = array();
$string = preg_replace('/[\pP]/u', '', trim(preg_replace('/\s\s+/iu', '', mb_strtolower($string))));
$matchWords = array_filter(explode(' ',$string) , function ($item) use ($stopwords) { return !($item == '' || in_array($item, $stopwords)
|| mb_strlen($item) <= 2 || is_numeric($item));});
$wordCountArr = array_count_values($matchWords);
// <p><p>
arsort($wordCountArr);
return array_keys(array_slice($wordCountArr, 0, 10)); }
figured it out ! Thanks
function generateKeywords($str)
{
$min_word_length = 3;
$avoid = ['the','to','i','am','is','are','he','she','a','an','and','here','there','can','could','were','has','have','had','been','welcome','of','home',' ','“','words','into','this','there'];
$strip_arr = ["," ,"." ,";" ,":", "\"", "'", "“","”","(",")", "!","?"];
$str_clean = str_replace( $strip_arr, "", $str);
$str_arr = explode(' ', $str_clean);
$clean_arr = [];
foreach($str_arr as $word)
{
if(strlen($word) > $min_word_length)
{
$word = strtolower($word);
if(!in_array($word, $avoid)) {
$clean_arr[] = $word;
}
}
}
return implode(',', $clean_arr);
}
This one seems very nice and comprehensive https://www.beliefmedia.com.au/create-keywords
Just make sure to change this line
$string = preg_replace('/[^\p{L}0-9 ]/', ' ', $string);
to
$string = preg_replace('/[^\p{L}0-9 ]/u', ' ', $string);
To support other langages (e.g Arabic)
And also better to use mb_strlen
If the string is in html format you can add the
strip_tags($str);
Before
$min_word_length = 3;
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"
I have made a script to highlight a word in a string. The script is below.
function highlight_text($text, $words){
$split_words = explode( " " , $words );
foreach ($split_words as $word){
$color = '#FFFF00';
$text = preg_replace("|($word)|Ui", "<span style=\"background:".$color.";\">$1</span>", $text );
}
return $text;
}
$text = '*bc';
$words = '*';
echo highlight_text($text, $words);
When running the script, I got the following error:
Warning: preg_replace(): Compilation failed: nothing to repeat at offset 1
Can anyone help me?
This can help you:
<?php
function highlight_text($text, $words){
$split_words = explode( " " , $words );
foreach ($split_words as $key=>$word){
if (preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $word))// looking for special characters
{
$word = preg_quote($word, '/');// if found output \ before that
}
$color = '#FFFF00';
$text = preg_replace("|($word)|Ui", "<span style=\"background:".$color.";\">$1</span>", $text );
}
return $text;
}
$text = '*bc';
$words = '*';
echo highlight_text($text, $words);
change "*" to "\*" and profit.
You can check if special character in function highlight_text
like:
function highlight_text($text, $words){
$split_words = explode( " " , $words );
foreach ($split_words as $word){
$str = '';
$word = str_split($word);
foreach ($word as $c) {
if ($c == '*') {
$str .= '\*';
}
else {
$str .= $c;
}
}
$color = '#FFFF00';
$text = preg_replace("|($str)|Ui", "<span style=\"background:".$color.";\">$1</span>", $text );
}
return $text;
}
Change your code to
function highlight_text($text, $words){
$split_words = explode( " " , $words );
foreach ($split_words as $word){
$color = '#FFFF00';
$word = preg_quote($word, '/');
$text = preg_replace("|$word|Ui", "<span style=\"background:".$color.";\">$0</span>", $text );
}
return $text;
}
$text = '*bc';
$words = '*';
echo highlight_text($text, $words);
then will be ok.
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;
}
Note that I used this with wordpress.
I added this function to functions.php:
function string_limit_words($string, $word_limit)
{
$words = explode(' ', $string, ($word_limit + 1));
if(count($words) > $word_limit)
array_pop($words);
return implode(' ', $words);
}
I added this to my html:
<?php if ( $woo_options['woo_post_content_home'] == "true" ) the_content(); else $excerpt = get_the_excerpt(); echo string_limit_words($excerpt,38); ?>
What this does is shortens the text to the number of words specified (in this sample its 38). What I want to do is add [...] after those 38 words. Any suggestions on how I can do this?
Regards,
Change it to
function string_limit_words($string, $word_limit)
{
$words = explode(' ', $string, ($word_limit + 1));
if(count($words) > $word_limit)
{
array_pop($words);
$words[] = '[...]';
}
return implode(' ', $words);
}
Uh...
function string_limit_words($string, $word_limit)
{
$words = explode(' ', $string, ($word_limit + 1));
if(count($words) > $word_limit)
array_pop($words);
return implode(' ', $words) . '...';
}
Just
echo string_limit_words($excerpt,38) . " ...";
should suffice.
You can modify the function like this so it will add the ellipses only when shorten the phrase.
function string_limit_words($string, $word_limit)
{
$ellipses = '';
$words = explode(' ', $string, ($word_limit + 1));
if(count($words) > $word_limit) {
array_pop($words);
$ellipses = ' ...';
}
$newString = implode(' ', $words) + $ellipses;
return $newString
}