I'm developing within Wordpress but my PHP knowledge is minimal, The title is showing only the 1st word, how to I change it? this is where I believe its being restricted to the 1st word.
function ShortenTitle($title){
// Change to the number of characters you want to display
$chars_max = 100;
$chars_text = strlen($title);
$title = $title."";
$title = substr($title,0,$chars_max);
$title = substr($title,0,strrpos($title,' '));
if ($chars_title > $chars_max)
{
$title = $title."...";
}
return $title;
}
function limit_content($str, $length) {
$str = strip_tags($str);
$str = explode(" ", $str);
return implode(" " , array_slice($str, 0, $length));
}
The trim function removes whitespace from the end of the string, I assume this is what you are trying to do with this
$title = substr($title,0,strrpos($title,' '));
Also, you should probably trim before computing the length, just to be safe/accurate. Try this:
function ShortenTitle($title){
// Change to the number of characters you want to display
$chars_max = 100;
$new_title = substr(trim($title),0,$chars_max);
if (strlen($title) > strlen($new_title)) {
$new_title .= "...";
}
return $new_title;
}
if ($chars_title > $chars_max) should be if ($chars_text > $chars_max)
Try this:
function ShortenTitle($title) {
$title = trim($title);
$chars_max = 100;
if (strlen($title) > $chars_max) {
$title = substr($title, 0, $chars_max) . "...";
}
return $title;
}
Cleaned it up a bit.
Related
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"
A have something like this. It works fine, but I have been tried 2 hours to cut search result - 100 str before $word and 100 after.
How can I make this?
$word = $_POST["search"];
$sql_events = mysql_query("SELECT * FROM events WHERE event_title LIKE '%" . $word . "%' OR event_desc LIKE '%" . $word ."%'");
function highlightWords($content, $word){
if(is_array($search)){
foreach ( $search as $word ){
$content = str_ireplace($word1, '<span>'.$word1.'</span>', $content);
}
} else {
$content = str_ireplace($word, '<span>'.$word.'</span>', $content);
}
return $content;
}
while($row = mysql_fetch_array($sql_events)){
$content = $row["event_desc"];
$result = highlightWords($content, $word);
echo '<li>
<H3>'.$row['event_title'].'</H3>
<div class="text">'.$result .'...</div>
</li>';
}
You need this regular expression:
[\d\D]{0,100}word[\d\D]{0,100}
Where word is the main word :). Here it is implemeted with your code:
$content = $row["event_desc"];
$word_in_regexp = quotemeta($content);
preg_match("/[\d\D]{0,100}$word_in_regexp[\d\D]{0,100}/i", $content, $matches);
$content = $matches[0];
We use quotemeta() in case $content contains characters like [, (, \ etc.
$wordpos1 = (mb_strpos($content, $word) - 100);
if ($wordpos1 < 0){
$wordpos1 = 0;
} else {
$wordpos1 = (mb_strpos($content, $word) - 100);
}
$wordpos2 = (mb_strpos($content, $word) + 400);
$resText = mb_substr($content, $wordpos1, $wordpos2);
$result = highlightWords($resText, $word);
And it's works to me :)
I am trying to make a function that cuts the white spaces in a string and ads punctuation if there isn't any.
This is my test string:
$test = 'Hey there I am traa la la ';
I want it to turn into this:
$test = 'Hey there I am traa la la.';
Here is the function I have tried:
function test($mytrim){
for($i = 0; $i <= 5; $i++){
if(substr($mytrim, 0, -1) == ''){
$mytrim = substr($mytrim, 0, -1);
}
}
$punct = array(".",",","?","!");
if(!in_array($mytrim, $punct)){ $mytrim .= '.'; }
return $mytrim;
}
It returns this:
$mytrim = 'Hey there I am traa la la. .';
Any ideas why it is not working?
PHP has a built in trim function. as for the punctuations, your code should work fine (appending).
Code sample :
<?php
$testString = " hello world ";
$trimmedString = trim($testString); // will contain "hello world"
$lastChar = substr($trimmedString, strlen($trimmedString)-1); // will be "d"
$punct = array(".",",","?","!");
if(!in_array($lastChar, $punct))
echo $trimmedString.'.'; //will output "hello world."
function test ($string)
{
$string = trim($string);
if ((substr($string, -1)) != ".")
{
$string .= ".";
}
}
function adspunctuation($str)
{
$str = trim($str) . (substr($str, -1)!='.' ? '.' : '');
return $str;
}
I have a set of articles, in which I want to style the first letter from each article (with CSS).
the articles usually start with a paragrah, like:
<p> bla bla </p>
So how could I wrap the first letter from this text within a <span> tag ?
Unless you need to do something extremely fancy, there's also the :first-letter CSS selector.
<?php
$str = '<p> bla bla </p>';
$search = '_^<p> *([\w])(.+) *</p>$_i';
$replacement = '<p><span>$1</span>$2</p>';
$new = preg_replace( $search, $replacement, $str );
echo $new."\n";
You can do this in all CSS.
CSS supports "Pseudo-Elements" where you can choose the first letter / first word and format it differently from the rest of the document.
http://www.w3schools.com/CSS/CSS_pseudo_elements.asp
There's a compatibility chart; some of these may not work in IE 6
http://kimblim.dk/css-tests/selectors/
you could add a Php span but might not be as clean
$s = " la la ";
$strip = trim(strip_tags($s));
$t = explode(' ', $strip);
$first = $t[0];
// then replace first character with span around it
$replace = preg_replace('/^?/', '$1', $first);
// then replace the first time of that word in the string
$s = preg_replace('/'.$first.'/', $replace, $s, 1);
echo $s;
//not tested
I've not found a versatile method yet, but a traditional code implementation (that may be slower) works:
function pos_first_letter($haystack) {
$ret = false;
if (!empty($haystack)) {
$l = strlen($haystack);
$t = false;
for ($i=0; $i < $l; $i++) {
if (!$t && ($haystack[$i] == '<') ) $t = true;
elseif ($t && ($haystack[$i] == '>')) $t = false;
elseif (!$t && !ctype_space($haystack[$i])) {
$ret = $i;
break;
}
}
}
return $ret;
}
Then call:
$i = pos_first_letter( $your_string );
if ($i !== false) {
$output = substr($s, 0, $i);
$output .= '<span>' . substr($s, $i, 1) . '</span>';
$output .= substr($s, $i+1);
}
How can i substr 20 chars from $xbio and get only complete words?
$xbio = 'word1 ord2 word3 word4 and so on';
echo ''.substr($xbio, 0, 20).'...';
TY
Found this searching stackoverflow - tell me what do you think please:
<? $xbio = preg_replace('/\s+?(\S+)?$/', '', substr($xbio, 0, 50)); ?>
This is the function i always use:
# advanced substr
function gen_string($string,$min) {
$text = trim(strip_tags($string));
if(strlen($text)>$min) {
$blank = strpos($text,' ');
if($blank) {
# limit plus last word
$extra = strpos(substr($text,$min),' ');
$max = $min+$extra;
$r = substr($text,0,$max);
if(strlen($text)>=$max) $r=trim($r,'.').'...';
} else {
# if there are no spaces
$r = substr($text,0,$min).'...';
}
} else {
# if original length is lower than limit
$r = $text;
}
return $r;
}
preg_match('/^([a-zA-Z0-9 ]{1,20})\\b/', $xbio, $matches);
echo $matches[1];
This is a function that i use for this kind of task:
function truncate($str, $maxLength, $append = '...') {
if (strlen($str) > $maxLength) {
$str = substr($str, 0, $maxLength);
$str = preg_replace('/\s+.*?$/', '', $str); // this line is important for you
$str = trim($str);
$str .= $append:
}
return $str;
}