This is in wordpress (not sure that makes a difference)
This bit of php outputs the post title
<?php echo $data['nameofpost']; ?>
It's simple text which can be anywhere up to 100 chars long. What i'd like is if the chars outputted are over 20 long to display '...' or simply nothing at all.
Thanks
After you check the string length with strlen use substr
$string = "This is a large text for demonstrations purposes";
if(strlen($string) > 20) $string = substr($string, 0, 20).'...';
echo $string;
Outputs
"This is a large text..."
Another way to cut the string off at the end of a word is with a regex. This one is set to cut off at 100 characters or the nearest word break after 100 characters:
function firstXChars($string, $chars = 100)
{
preg_match('/^.{0,' . $chars. '}(?:.*?)\b/iu', $string, $matches);
return $matches[0];
}
<?php
function abbreviate($text, $max) {
if (strlen($text)<=$max)
return $text;
return substr($text, 0, $max-3).'...';
}
?>
<?php echo htmlspecialchars(abbreviate($data['nameofpost'], 20)); ?>
A common improvement would be to try to cut the string at the end of a word:
if (strlen($text)<=$max)
return $text;
$ix= strrpos($text, ' ', $max-2);
if ($ix===FALSE)
$text= substr($text, 0, $max-3);
else
$text= substr($text, 0, $ix);
return $text.'...';
If you are using UTF-8 strings you would want to use the mb_ multibyte versions of the string ops to count characters more appropriately.
in your theme file use something like this
try using <div class="teaser-text"><?php the_content_limit(100, ''); ?></div>
then in the functions.php files, use this
function the_content_limit($max_char, $more_link_text = '(more...)', $stripteaser = 0, $more_file = '')
{
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
$content = strip_tags($content);
if (strlen($_GET['p']) > 0)
{
echo "<div>";
echo $content;
echo "</div>";
}
else if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char )))
{
$content = substr($content, 0, $espacio);
$content = $content;
echo "<div>";
echo $content;
echo "...";
echo "</div>";
}
else {
echo "<div>";
echo $content;
echo "</div>";
}
}
good luck :)
if(count($data['nameofpost']) > 20)
{
echo(substr($data['nameofpost'], 0, 17)."...");
}
For $data['nameofpost'] greater then 20 chars it will output the first 17 plus three dots ....
Related
I want string format with incremental numbers. I've strings starting with alphabets and containing numbers with few leading 0's.
$string = M001; //input
$alf= trim(str_replace(range(0,9),'',$string)); //removes number from string
$number = preg_replace('/[A-Za-z]+/', '', $string);// removes alphabets from the string
$number+=1;
$custom_inv_id = $alf.$number;
Expected result:
input M002 output M003
input A00003 output A00004
Using above code if input is M002, I'm getting output as M3. How I can get M003? Number of 0's is not fixed.
Use PHP preg_match or str_replace and try this code :-
$str='M001';
preg_match('!\d+!', $str, $matches);
$num=(int)$matches[0];
$num++;
echo str_replace((int)$matches[0],'',$str);
echo $num;
Demo
<?php
$tests = ['M0', 'M1', 'M001', 'M9', 'M09', 'M010',
'M2M0', 'M2M1', 'M2M001', 'M2M9', 'M2M09', 'M2M010',
'M2M', 'MM', '9M'];
foreach ($tests as $string) {
if (preg_match('/([\w\W]+)([0-9]+)$/', $string, $matches)) {
$output_string = $matches[1] . ($matches[2] + 1);
echo '<p>' . $string . ' => ' . $output_string . '</p>';
} else {
echo '<p>' . $string . ' (nothing to increment)</p>';
}
}
$a = 'm002';
$pattern = '#(?P<word>[A-Za-z0]+)(?P<digtt>[1-9]+)#';
preg_match($pattern, $a, $matches);
$final = $matches['word'].(string)($matches['digtt']+1);
echo $final;
You can use the sprintf and preg_match functions to get your expected result.
First: Split your string with preg_match to seperated values to work with
Second: Format a new string with sprintf
http://php.net/manual/en/function.sprintf.php
http://php.net/manual/en/function.preg-match.php
function increase($string, $amount = 1) {
$valid = preg_match("#^(.)(0+)?(\d+)$#s", $string, $matches);
if($valid) {
list($match, $char, $zero, $integer) = $matches;
$integer += $amount;
return sprintf("%s%'.0" . (strlen($zero)+1) . "d", $char, $integer);
}
return null;
}
echo increase("M00001"); // M00002
echo increase("A001", 5); // A006
i hope this can help you . i have made some thing dynamic make M% also dynamic
<?php
$vl = "A00004";
$number = substr($vl ,1);
$num= substr_count($vl,0);
$num++;
$number++;
$string = "M%'. 0".$num."d";
echo sprintf($string, $number);
?>
i got this result
M00005
As leading 0 is copied, I would do it like this. It works if the leading chars is also lowercase. It's also a non-regex and non-array way.
$str = "M0099";
$num = ltrim($str, "a..zA..Z0");
$new = str_replace($num, $num + 1, $str);
Output:
echo $new; // string(6) "M00100"
I am trying to remove all leading and trailing <br> in a string using PHP.
Here is an example
<br><br>
Hello<br>
World<br>
<p>This is a message<br>...</p>
<br><br><br><br>
I want to return
Hello<br>
World<br>
<p>This is a message<br>...</p>
I tried to do the following
echo trim($str, '<br>');
But it does not remove them. How can I remove the new line html code?
Use preg_replace with the beginning ^ and end $ anchors:
$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/', '', $string);
Or for multiple lines:
$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/m', '', $string);
You could also trim() it multiple times:
while($string !== ($string = trim($string, '<br>'))){}
This function does the job. Also applicable to anything else really.
//remove all leading and trailing occurences of needle ($n) from haystack ($h)
function trimAll($h, $n){
if(!$h = trim($h,$n)){
trimAll($h, $n);
}
return $h;
}
I wrote this function that will do the job a little better as it gives me more flexibility on what characters to remove and when this function by default will first remove the leading/trailing characters in order:
any tabs
any new lines
any
any
any tabs
any new lines
function trimString($str, $myList = array("\t","\n", "<br>","<br />", "\t","\n") ){
if( ! is_array($myList) ){
$charsToTrim[] = $chr;
} else {
$charsToTrim = $myList;
}
foreach($charsToTrim as $chr){
$len = strlen($chr);
$nlen = $len * -1;
while( substr($str, 0, $len) == $chr){
$str = trim(substr($str, $len));
}
while( substr($str, $nlen) == $chr){
$str = trim(substr($str, 0, $nlen));
}
}
return $str;
}
to use
// default use case
echo trimString($message);
or
//remove only one string
echo trimString($message, '<br>'); // remove only the leading training '<br>'
or
//remove more than 1 string in order
echo trimString($message, array('<br>'<br />') );
I hope this helps someone out there :)
$p=array(
'<br><br>',
'Hello<br>',
'World<br>',
'<p>This is a message<br>...</p>',
'<br><br><br><br>'
);
function trimdeluxe($str, $sub)
{
$parts=explode($sub, $str);
for ($x=0; $x<2; $x++) {
foreach ($parts as $i=>$v) {
if (!strlen($v)) {
unset($parts[$i]);
} else {
break;
}
}
$parts=array_reverse($parts);
}
return implode($sub,$parts);
}
foreach ($p as $str) {
print $str . ' -> ' . trimdeluxe($str, '<br>') . "\n";
}
I am outputting a string using the substr function and limiting the output to 100 characters. The problem is sometimes the string contains a URL with over 100 characters.
Does anyone have any advice on how I can output the URL within the 100 character limit by replacing the text link to something generic like [Link]
My code:
<?php
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
if(preg_match($reg_exUrl, $content, $url)) {
$content = preg_replace($reg_exUrl, "Link", $content);
if (strlen($content) > 100) {
echo substr($content, 0, 100).'...';
}
} else {
if (strlen($content) > 100) { echo substr(stripslashes($content), 0, 100).'...'; } else { echo stripslashes($content); }
}
?>
if(strlen($url[0]) > 100) {
$content = preg_replace($reg_exUrl, "Link", $content);
}else{
$content = preg_replace($reg_exUrl, "{$url[0]}", $content);
}
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;
}
I have text stored in the php variable $text. This text can be 100 or 1000 or 10000 words. As currently implemented, my page extends based on the text, but if the text is too long the page looks ugly.
I want to get the length of the text and limit the number of characters to maybe 500, and if the text exceeds this limit I want to provide a link saying, "Read more." If the "Read More" link is clicked, it will show a pop with all the text in $text.
This is what I use:
// strip tags to avoid breaking any html
$string = strip_tags($string);
if (strlen($string) > 500) {
// truncate string
$stringCut = substr($string, 0, 500);
$endPoint = strrpos($stringCut, ' ');
//if the string doesn't contain any space then it will cut without word basis.
$string = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);
$string .= '... Read More';
}
echo $string;
You can tweak it further but it gets the job done in production.
$num_words = 101;
$words = array();
$words = explode(" ", $original_string, $num_words);
$shown_string = "";
if(count($words) == 101){
$words[100] = " ... ";
}
$shown_string = implode(" ", $words);
There is an appropriate PHP function: substr_replace($text, $replacement, $start).
For your case, because you already know all the possibilities of the text length (100, 1000 or 10000 words), you can simply use that PHP function like this:
echo substr_replace($your_text, "...", 20);
PHP will automatically return a 20 character only text with ....
Se the documentation by clicking here.
I have combine two different answers:
Limit the characters
Complete HTML missing tags
$string = strip_tags($strHTML);
$yourText = $strHTML;
if (strlen($string) > 350) {
$stringCut = substr($post->body, 0, 350);
$doc = new DOMDocument();
$doc->loadHTML($stringCut);
$yourText = $doc->saveHTML();
}
$yourText."...<a href=''>View More</a>"
Simple use this to strip the text :
echo strlen($string) >= 500 ?
substr($string, 0, 490) . ' [Read more]' :
$string;
Edit and finally :
function split_words($string, $nb_caracs, $separator){
$string = strip_tags(html_entity_decode($string));
if( strlen($string) <= $nb_caracs ){
$final_string = $string;
} else {
$final_string = "";
$words = explode(" ", $string);
foreach( $words as $value ){
if( strlen($final_string . " " . $value) < $nb_caracs ){
if( !empty($final_string) ) $final_string .= " ";
$final_string .= $value;
} else {
break;
}
}
$final_string .= $separator;
}
return $final_string;
}
Here separator is the href link to read more ;)
<?php $string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";
if (strlen($string) > 25) {
$trimstring = substr($string, 0, 25). ' readmore...';
} else {
$trimstring = $string;
}
echo $trimstring;
//Output : Lorem Ipsum is simply dum [readmore...][1]
?>
This method will not truncate a word in the middle.
list($output)=explode("\n",wordwrap(strip_tags($str),500),1);
echo $output. ' ... Read more';
Limit words in text:
function limitTextWords($content = false, $limit = false, $stripTags = false, $ellipsis = false)
{
if ($content && $limit) {
$content = ($stripTags ? strip_tags($content) : $content);
$content = explode(' ', $content, $limit+1);
array_pop($content);
if ($ellipsis) {
array_push($content, '...');
}
$content = implode(' ', $content);
}
return $content;
}
Limit chars in text:
function limitTextChars($content = false, $limit = false, $stripTags = false, $ellipsis = false)
{
if ($content && $limit) {
$content = ($stripTags ? strip_tags($content) : $content);
$ellipsis = ($ellipsis ? "..." : $ellipsis);
$content = mb_strimwidth($content, 0, $limit, $ellipsis);
}
return $content;
}
Use:
$text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.";
echo limitTextWords($text, 5, true, true);
echo limitTextChars($text, 5, true, true);
Basically, you need to integrate a word limiter (e.g. something like this) and use something like shadowbox. Your read more link should link to a PHP script that displays the entire article. Just setup Shadowbox on those links and you're set. (See instructions on their site. Its easy.)
Another method: insert the following in your theme's function.php file.
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_trim_excerpt');
function custom_trim_excerpt($text) { // Fakes an excerpt if needed
global $post;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$text = strip_tags($text);
$excerpt_length = x;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words) > $excerpt_length) {
array_pop($words);
array_push($words, '...');
$text = implode(' ', $words);
}
}
return $text;
}
You can use this.
<?php
$images_path = 'uploads/adsimages/';
$ads = mysql_query("select * from tbl_postads ORDER BY ads_id DESC limit 0,5 ");
if(mysql_num_rows($ads)>0)
{
while($ad = mysql_fetch_array($ads))
{?>
<div style="float:left; width:100%; height:100px;">
<div style="float:left; width:40%; height:100px;">
<li><img src="<?php echo $images_path.$ad['ads_image']; ?>" width="100px" height="50px" alt="" /></li>
</div>
<div style="float:left; width:60%; height:100px;">
<li style="margin-bottom:4%;"><?php echo substr($ad['ads_msg'],0,50);?><br/> read more..</li>
</div>
</div>
<?php }}?>
I Guess this will help you fix your problem please check under given Function : 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
#return string
function trim_text($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}//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;}
This worked for me.
// strip tags to avoid breaking any html
$string = strip_tags($string);
if (strlen($string) > 500) {
// truncate string
$stringCut = substr($string, 0, 500);
$endPoint = strrpos($stringCut, ' ');
//if the string doesn't contain any space then it will cut without word basis.
$string = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);
$string .= '... Read More';
}
echo $string;
Thanks #webbiedave