substr only with string greater than 4 characters

1

I use substr this way:

$conta = "ABCDE";
echo substr($conta, -1);

It returns me ABCD , I wanted to know how to execute substr only in string that contains more than 4 characters.

    
asked by anonymous 31.05.2017 / 18:59

4 answers

5

I noticed that everyone used -1 , but this would make something like:

  • ABCDEFGH will return H
  • ABCDEFGHI will return HI

I really wondered if you want to get the share of string coming after of the 4 characters or if you want to limit to 4 characters if you want to limit to 4 then I think you should do an adaptation to this:

$conta = "ABCDE";
echo strlen($conta) > 4 ? substr($conta, 0, 4) : $conta;

Then in the example in ideone you may notice that this returns:

$conta = "ABCDEFGHIJKLM";

echo strlen($conta) > 4 ? substr($conta, -1) : $conta, PHP_EOL; // M

echo strlen($conta) > 4 ? substr($conta, 0, 4) : $conta, PHP_EOL; // ABCD
    
31.05.2017 / 19:43
5

Try to do this:

$conta = "ABCDE";
echo strlen($conta) > 4 ? substr($conta, -1) : $conta;
    
31.05.2017 / 19:09
4

Just make a if by counting the characters with the function strlen()

$conta = "ABCDE";
if(strlen($conta) > 4){
    $conta = substr($conta, -1);
}
echo $conta;
    
31.05.2017 / 19:08
1

You can use the strlen function to count STRLEN

<?php
$str = 'abcdef';
echo strlen($str); // 6 caracteres

$str = ' ab cd ';
echo strlen($str); // 7 caracteres, pôs espaço conta
?>
    
31.05.2017 / 19:08