substr only with string greater than 4 character

Asked

Viewed 251 times

1

Use the substr thus:

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

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

  • Tried to count the characters or this general some problem or is not yet possible to do?

  • 2

    We have downvotes maniacs here?

  • Why did you zero in on our response?

  • 1

    You want to take everything that comes after these 4 characters, or you want to limit it to 4 characters?

4 answers

5

Try to do it this way:

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

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 wanted to take the part from string coming afterward 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 make an adaptation to this:

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

So in the example in ideone you may notice that it returns this:

$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
  • 1

    Very well observed. All were on the impulse of the AP to have already placed the erroneous call of the kkk function

  • 'Cause that’s a minor detail in the question.

  • @jbueno yes, I agree that within the question was answered exactly what was asked (within the understanding), but answered only by same effort, this does not invalidate anything that was answered by the others, it is only an additional.

  • 1

    Yes, yes. My comment was in response to Anderson, your answer is great.

  • 1

    preg_match('~(\w{4})\w*(\w)~', $conta, $match); :D

  • 1

    @Legal Guilhermelautert to add the modifier u ae supports Unicode :D

  • Well observed, I hadn’t even noticed

Show 2 more comments

4

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

$conta = "ABCDE";
if(strlen($conta) > 4){
    $conta = substr($conta, -1);
}
echo $conta;

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
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.