How can I get the first n characters of a string in PHP? What's the fastest way to trim a string to a specific number of characters, and append '...' if needed?
php
string
ellipsis
truncation
Answers
4
You need a Ajax call to pass the JS value into php variable
JS Code will be (your js file)
var jsString="hello";
$.ajax({
url: "ajax.php",
type: "post",
data: jsString
});
And in ajax.php (your php file) code will be
$phpString = $_POST['data']; // assign hello to phpString
Thursday, November 10, 2022
5
How about:
if (strlen($input) > $maxLen) {
$characters = floor($maxLen / 2);
return substr($input, 0, $characters) . '...' . substr($input, -1 * $characters);
}
Wednesday, August 3, 2022
5
Here's a neat solution:
String upToNCharacters = s.substring(0, Math.min(s.length(), n));
Opinion: while this solution is "neat", I think it is actually less readable than a solution that uses if
/ else
in the obvious way. If the reader hasn't seen this trick, he/she has to think harder to understand the code. IMO, the code's meaning is more obvious in the if
/ else
version. For a cleaner / more readable solution, see @paxdiablo's answer.
Saturday, November 26, 2022
4
Use cut
. Eg. to strip the first 4 characters of each line (i.e. start on the 5th char):
tail -f logfile | grep org.springframework | cut -c 5-
Wednesday, November 16, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
php
string
ellipsis
truncation
Update:
Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):
So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'
Update 2:
Or as function:
Update 3:
It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the
wordwrap
function: