I have this function that limits text, lets say to 50 chars like above:
$bio = limit_text($bio, 50);
function limit_text($text, $length){ // Limit Text
if(strlen($text) > $length) {
$text = substr($text, 0, strpos($text, ' ', $length));
}
return $text;
}
This should echo something like:
Hello, this is a text limited to 50 chars and it's a great ...
The problem is that the function shows the last punctuation mark which does not look professional. Like in this example:
Hello, this is a text limited to 50 chars and it has a comma at the end, ...
Is there any way to make the function not show the last punctuation mark?
Thank you!
<?php
$text="Hello, this is a text limited to 50 chars and it has a comma at the end.";
//$text = preg_replace("/[^a-zA-Z 0-9]+/", " ", $text); //bad
$text=rtrim($text,",.;:- _!$&#"); // good select what you want to remove
echo $text;
You could a function like this to parse the $text
first:
$text = preg_replace("/[^a-zA-Z 0-9]+/", " ", $text);
This should get the job done, ctype_punct
checks for all non-alphanumeric characters in a given string.
function limit_text($text, $length){ // Limit Text
if(strlen($text) > $length) {
$text = substr($text, 0, strpos($text, ' ', $length));
if(ctype_punct(substr($text,-1))
$text=substr($text,0,-1);
}
return $text;
}
return rtrim($text, ',') . '...'; // That is if you only care about the ',' character