Solved

Substring in PHP

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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
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…
The viewer will learn how to count occurrences of each item in an array.
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 …

746 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

11 Experts available now in Live!

Get 1:1 Help Now