I am trying to limit the amount of text/data is being shown from MySQL not MySQL LIMIT but limiting it on the actual page like most blogs do. After certain text point they just display ...more, I know there is a function to do this in PHP but I am unable to remember its name could some one help me out with it?
if(strlen($text)>1000){
$text=substr($text,0,1000).' Read more';
}
you should understand that it can cut words and tags too.
SELECT LEFT(content, 1000) FROM blog
If you load entire content for example 30 000 chars and do substr(), you are wasting memory in order to show only 1000.
You could use a function like this (taken from http://brenelz.com/blog/creating-an-ellipsis-in-php/):
function ellipsis($text, $max=100, $append='…')
{
if (strlen($text) <= $max) return $text;
$out = substr($text,0,$max);
if (strpos($text,' ') === FALSE) return $out.$append;
return preg_replace('/\w+$/','',$out).$append;
}
This won't cut a word in half like substr.
There are a few ways to do it, the easiest probably being substr()
$short = substr($long, 0, $max_len);
string substr ( string $string , int $start [, int $length ] )
It accepts two arguments. The first is the string that you would like to trim. The second is the length, in characters of what you'd like returned.
http://php.net/manual/en/function.substr.php
Apply the wrap() function to get your shortened text, and replace "99" with the number of characters you want to limit it to.
function wrap($string) {
$wstring = explode("\n", wordwrap($string, 99, "\n") );
return $wstring[0];
}
<?
$position=14; // Define how many character you want to display.
$message="You are now joining over 2000 current";
$post = substr($message, 0, $position);
echo $post;
echo "...";
?>
This result shows 14 characters from your message
Related
I've got a problem. This is my PHP code :
$extract = $query;
$extractpoint = strrchr($extract, ".");
So, $extract is a parse_url of my website address.
Exemple : http://test.com?param.6
$extract = param.6 and $extractpoint = .6
BUT, I want a solution to have only the 6, without the point.
Can you help me with that ?
The easiest solution would be restructuring the URL. I that is not possible though you can use strpos to find the position of your specific character and then use substr to select the characters after it.
$extract = 'param.6';
echo substr($extract, strpos($extract, '.') + 1);
Demo: https://3v4l.org/CudTAG
(The +1 is because it returns the position of the match and you want to be one place past that)
There are different ways:
Filter only numbers:
$int = filter_var($extractpoint, FILTER_SANITIZE_NUMBER_INT);
Replace the point
$int = str_replace('.', '', $extractpoint)
//$int = str_replace('param.', '', $extractpoint)
Use regex
/[0-9+]/'
strrchr() results the count of the last instance of a character in a string. In order to get the next character add 1 to the count. Then use substr() to extract the next character from the string.
http://php.net/manual/en/function.strrchr.php
http://php.net/manual/en/function.substr.php
For example, 3 string are the following :
##7##
##563##
##120058##
How can I get those number like this :
echo first number is 7
echo second number is 563
echo third number is 120058
Thank you very much!
$numberAsString = trim($string, '##')
Is probably the easiest and fastest in this case. The output is still a string in this case, but in most cases that doesn't really matter. If it does in your case, you can use (int), (float) or the like to get it to the correct type.
Of course, regex would also be possible, e.g.:
$didMatch = preg_match('/#+([^#]+)#+/', $string, $matches);
Another possibility still is first extract the remaining part after the initial 2 # and then cast to a number, which seems to be always int in this case:
$number = (int)substr($string, 2);
Still another possibility would be to go by the count of the characters and just use substr like:
$numberAsString = substr($string, 2, -2);
Or you could be creative and use something like explode + implode + array functions:
$numberAsString = array_slice(explode('#', implode('', array_slice(explode('#', $string), 2))), 0, -2);
Of course, this last one is purely to show that it can be done in various ways, as it's very inefficient and impractical, but there are surely dozens of other ways.
In case you use this in a tight loop or somewhere where performance really matters, I would benchmark different possibilities - on a guess, I'd say that either the trim or the pure substring solution would be the fastest.
$str = "##563##";
preg_match("|\d+|", $str, $res);
print_r($res);
Just call the filter_var() function it will return the number only.
Whatever the input is, it will only filter the number for you!
filter_var("##120058##", FILTER_SANITIZE_NUMBER_INT) // return 120058
filter_var("*##20kkk", FILTER_SANITIZE_NUMBER_INT) // return 20
I am trying to learning something about PHP, and I don't know how to do it, something like this:
I have a string:
$text = 'This is your post number [postnumb], This is [postnumb], And this is your post number [postnumb].';
And with PHP I want to change the string [postnumb] to the number of post:
$textchanged = 'This is your post number 1, This is your post number 2, This is your post number 3.';
Any help for me? Thanks.
Using preg_replace(), you can use the 4th argument to limit the replacement to the first occurrence. Combine this with a loop that will run until there are no occurrences remaining, and you can achieve what you're after:
$text = 'This is your post number [postnumb], This is [postnumb], And this is your post number [postnumb].';
$i = 0;
while(true)
{
$prev = $text;
$text = preg_replace('/\[postnumb\]/', ++$i, $text, 1);
if($prev === $text)
{
// There were no changes, exit the loop.
break;
}
}
echo $text; // This is your post number 1, This is 2, And this is your post number 3.
str_replace("[postnumb]", 1, $text);
You can't set different numbers for [postnumb] using str_replace() (unless you do it manually for substrings).
preg_replace() should help you for that case, or using different tags for different numbers (like [postnumb2] and [postnumb]).
I'm trying to build a function to trim a string is it's too long per my specifications.
Here's what I have:
function trim_me($s,$max)
{
if (strlen($s) > $max)
{
$s = substr($s, 0, $max - 3) . '...';
}
return $s;
}
The above will trim a string if it's longer than the $max and will add a continuation...
I want to expand that function to handle multiple words. Currently it does what it does, but if I have a string say: How are you today? which is 18 characters long. If I run trim_me($s,10) it will show as How are yo..., which is not aesthetically pleasing. How can I make it so it adds a ... after the whole word. Say if I run trim_me($s,10) I want it to display How are you... adding the continuation AFTER the word. Any ideas?
I pretty much don't want to add a continuation in the middle of a word. But if the string has only one word, then the continuation can break the word then only.
So, here's what you want:
<?php
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function myTruncate($string, $limit, $break=".", $pad="...") {
// is $break present between $limit and the end of the string?
if(false !== ($breakpoint = strpos($string, $break, $limit))) {
if($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $string;
}
?>
Also, you can read more at http://www.the-art-of-web.com/php/truncate/
function trim_me($s,$max) {
if( strlen($s) <= $max) return $s;
return substr($s,0,strrpos($s," ",$max-3))."...";
}
strrpos is the function that does the magic.
I've named the function str_trunc. You can specify strict being TRUE, in which case it will only allow a string of the maximum size and no more, otherwise it will search for the shortest string fitting in the word it was about to finish.
var_dump(str_trunc('How are you today?', 10)); // string(10) "How are..."
var_dump(str_trunc('How are you today? ', 10, FALSE)); // string(14) "How are you..."
// Returns a trunctated version of $str up to $max chars, excluding $trunc.
// $strict = FALSE will allow longer strings to fit the last word.
function str_trunc($str, $max, $strict = TRUE, $trunc = '...') {
if ( strlen($str) <= $max ) {
return $str;
} else {
if ($strict) {
return substr( $str, 0, strrposlimit($str, ' ', 0, $max + 1) ) . $trunc;
} else {
return substr( $str, 0, strpos($str, ' ', $max) ) . $trunc;
}
}
}
// Works like strrpos, but allows a limit
function strrposlimit($haystack, $needle, $offset = 0, $limit = NULL) {
if ($limit === NULL) {
return strrpos($haystack, $needle, $offset);
} else {
$search = substr($haystack, $offset, $limit);
return strrpos($search, $needle, 0);
}
}
It's actually somehow simple and I add this answer because the suggested duplicate does not match your needs (but it does give some pointers).
What you want is to cut a string a maximum length but preserve the last word. So you need to find out the position where to cut the string (and if it's actually necessary to cut it at all).
As getting the length (strlen) and cutting a string (substr) is not your problem (you already make use of it), the problem to solve is how to obtain the position of the last word that is within the limit.
This involves to analyze the string and find out about the offsets of each word. String processing can be done with regular expressions. While writing this, it reminds me on some actually more similar question where this has been already solved:
Extract a fixed number of chars from an array, just full words (with regex)
How to get first x chars from a string, without cutting off the last word? (with wordwrap)
It does exactly this: Obtaining the "full words" string by using a regular expression. The only difference is, that it removes the last word (instead of extending it). As you want to extend the last word instead, this needs a different regular expression pattern.
In a regular expression \b matches a word-boundary. That is before or after a word. You now want to pick at least $length characters until the next word boundary.
As this could contain spaces before the next word, you might want to trim the result to remove these spaces at the end.
You could extend your function like the following then with the regular expression pattern (preg_replace) and the trim:
/**
* Cut a string at length while preserving the last word.
*
* #param string $str
* #param int $length
* #param string $suffix (optional)
*/
function trim_word($str, $length, $suffix = '...')
{
$len = strlen($str);
if ($len < $length) return $str;
$pattern = sprintf('/^(.{%d,}?)\b.*$/', $length);
$str = preg_replace($pattern, '$1', $str);
$str = trim($str);
$str .= $suffix;
return $str;
}
Usage:
$str = 'How are you today?';
echo trim_word($str, 10); # How are you...
You can further on extend this by reducing the minimum length in the pattern by the length of the suffix (as it's somehow suggested in your question, however the results you gave in your question did not match with your code).
I hope this is helpful. Also please use the search function on this site, it's not perfect but many gems are hidden in existing questions for alternative approaches.
I'm using the getExcerpt() function below to dynamically set the length of a snippet of text. However, my substr method is currently based on character count. I'd like to convert it to word count. Do I need to separate function or is there a PHP method that I can use in place of substr?
function getExcerpt()
{
//currently this is character count. Need to convert to word count
$my_excerptLength = 100;
$my_postExcerpt = strip_tags(
substr(
'This is the post excerpt hard coded for demo purposes',
0,
$my_excerptLength
)
);
return ": <em>".$my_postExcerpt." [...]</em>";}
}
Use str_word_count
Depending on the parameters, it can either return the number of words in a string (default) or an array of the words found (in case you only want to use a subset of them).
So, to return the first 100 words of a snippet of text:
function getExcerpt($text)
{
$words_in_text = str_word_count($text,1);
$words_to_return = 100;
$result = array_slice($words_in_text,0,$words_to_return);
return '<em>'.implode(" ",$result).'</em>';
}
If you want that your script should not ignore the period and comma and other punctuation symbols then you should adopt this approach.
function getExcerpt($text)
{
$my_excerptLength = 100;
$my_array = explode(" ",$text);
$value = implode(" ",array_slice($my_array,0,$my_excerptLength));
return
}
Note : This is just an example.Hope it will help you.Don't forget to vote if it help you.