Here I have a string: "status; status;" and so on... I need to cut the string from the status where string is longer than 100 chars
for example: "status; status; status; (here is longer than 100 chars) ..."
previously I did it with the array:
if($length_of_string > 100)
{
$number_of_elements = count($statuses_array);
echo $statuses_array[$number_of_elements-1];
echo ' ... ';
} else {
echo $string_of_statuses;
}
but it is not good
thank you in advance!
How about:
$l = strlen($status_string);
if ($l > 100) {
//Split string into array of statuses, to not break last status
$ls = explode(";",$status_string);
$new_status = "";
$i = 0;
//Check if there is room for the next status in $new_status without passing 100 chars
while (strlen($new_status) < 100) {
$new_status .= $ls[$i].";";
$i++;
}
$new_status = substr($new_status,0,-1)."...";
}
Edit: simplified code, as the last status apparently can surpass 100 chars, which actually makes it easier
If I am reading your question right, and I think I am: if a string is longer than 100 characters, append a ellipsis to the first 100 characters.
If so, then you don't necessarily need a regex
, or a preg_replace
. You can do it simply as follows:
$status_length = strlen($status_string);
$status = '';
if ($status_length > 100) {
//get the substring up to the first 100 characters:
$status = substr($status_string, 0, 100);
//now append the ellipsis to it:
$status .= '...';
}
echo $status;
your variable$variable_text="status; status; status; status; status; status; status; status; status; status; status; status; statwus; status; status; status; status; status;";
a number after you want to add "..."$characters=100;
count words in $variable_text$words_number=preg_split("/[\s]+/", $variable_text);
Add words to the variable $words. If characters in the variable $words is less than variable $characters(100) a word is added to variable $result. If hundredth character is in a word "sta(100)tus;" this word is not added to variable $result
for($i=0;$i<=count($words_number);$i++){
$words=$words." ".$words_number[$i];
if(strlen($words)<$characters){
$result=$words;
}
}
if your variable $variable_text is bigger than variable $result add " ..." at the end
if(strlen($result)<strlen($variable_text)){
$result=$result." ...";
}
show the resultecho $result;