Shorten a text string in PHP
Is there a way to trim a text string in PHP so it has a certain number of characters? For instance, if I had the string:
$string = "this is a string";
How could I trim it to say:
$newstring = "this is";
This is what I have so far, usingchunk_split()
, but it isn't working. Can anyone improve on my method?
function trimtext($text)
{
$newtext = chunk_split($text,15);
return $newtext;
}
I also looked at this question, but I don't really understand it.
Answer
Solution:
will do the job.
Take a look here.
Answer
Solution:
substr cuts words in half. Also if word contains UTF8 characters, it misbehaves. So it would be better to use mb_substr:
$string = mb_substr('word word word word', 0, 10, 'utf8').'...';
Answer
Solution:
You didn't say the reason for this but think about what you want to achieve. Here is a function for shorten a string word by word with or without adding ellipses at the end:
Answer
Solution:
You can call the function like this:
Would return:
This is a
Answer
Solution:
let's you take a portion of string consisting of exactly as much characters as you need.
Answer
Solution:
You can use this
function to get substring
Answer
Solution:
If you want to get a string with a certain number of characters you can use substr, i.e.
where $length is the given length of the new string.
Answer
Solution:
If you want an abstract for the first 10 words (you can use html in $text, before script there is strip_tags) use this code:
Answer
Solution:
My function has some length to it, but I like to use it. I convert the string int to a Array.
Or if the text is coming from an editor and you want to strip out the HTML tags.
Answer
Solution:
With elipsis (...) only if longer - and taking care of special language-specific characters: