Solved

Substring in PHP

Posted on 2008-06-15
3
772 Views
Last Modified: 2010-05-18
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
Comment
Question by:mawingho
3 Comments
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 240 total points
ID: 21791134
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
 
LVL 48

Assisted Solution

by:hernst42
hernst42 earned 20 total points
ID: 21791136
if (substr('CHH0A0606C3G', -3) == 'C3G') {
 ...
}
0
 
LVL 3

Assisted Solution

by:Fapiko
Fapiko earned 240 total points
ID: 21791320
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

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

791 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question