Reputation: 89
I created a PHP page that show names from a table, there is some names is too long, I want to make if $name
is 12 characters then replace what after 12 characters with ...
this is my code
$query= mysql_query("SELECT * FROM `table`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$name= $arr['name'];
echo '</br>';
echo $name;
}
How can I do it?
Upvotes: 0
Views: 126
Reputation: 4268
You can do it like this:-
<?php
$mystring = "this is a test string to check that";
if( strlen($mystring) >= 12)
{
$result= substr($mystring,0,12);
$result .='...';
}
echo $result;
?>
Upvotes: 1
Reputation: 76646
You can do something like this:
if( strlen($arr['name']) > 12)
{
substr($arr['name'],0,12)."...";
}
So, your code will look like:
$query= mysql_query("SELECT * FROM `table`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$name= $arr['name'];
echo '</br>';
if(strlen($name) > 12)
{
substr($name,0,12) . "...";
}
}
Upvotes: 1
Reputation: 5213
Try:
$name = (strlen($arr['name']) > 12) ? substr($arr['name'],0,12) . "..." : $arr['name'];
This is a conditional assignment. If $arr['name']
is greater than 12 characters, then it truncates it to 12 characters and adds "...". Otherwise, it uses the full name.
Upvotes: 3