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.
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.
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
Try to do this:
$conta = "ABCDE";
echo strlen($conta) > 4 ? substr($conta, -1) : $conta;
Just make a if
by counting the characters with the function strlen()
$conta = "ABCDE";
if(strlen($conta) > 4){
$conta = substr($conta, -1);
}
echo $conta;
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
?>