Solved

Substring in PHP

Posted on 2008-06-15
3
756 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 142

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

911 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now