• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 807
  • Last Modified:

Substring in PHP

If I have a string in PHP, for example
CHH0A0606C3G

How can I know whether the LAST 3 LETTER is C3G or not?

Thanks!
0
mawingho
Asked:
mawingho
3 Solutions
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
check out this:

$data = "CHH0A0606C3G";
$last_3_digits = substr($data, -3);
if ($last_3_digits == "C3G")
{ // last 3 digits are ok:
  echo "OK";
}
else
{ // last 3 digits are not ok:
  echo "FAILURE";
}

Open in new window

0
 
hernst42Commented:
if (substr('CHH0A0606C3G', -3) == 'C3G') {
 ...
}
0
 
FapikoCommented:
I don't know if this is true or not, but I've heard that using a negative number in substring is significantly slow so I've always used this function:
<?php
function right($string, $length) {
   return substr($string, strlen($string) - $length);
}
 
// Thus this would return 'C3G':
echo right('CHH0A0606C3G', 3);
?>

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now