Klaus Jasper
Klaus Jasper

Reputation: 89

PHP - If variable's character is number then do something

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

Answers (4)

roptch
roptch

Reputation: 225

if (strlen($name) > 12)
    $name = substr($name, 0, 12) . '...';

https://php.net/strlen

https://php.net/substr

Upvotes: 2

Vivek Sadh
Vivek Sadh

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

Amal Murali
Amal Murali

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

theftprevention
theftprevention

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

Related Questions