Substring in PHP

Posted on 2008-06-15
Medium Priority
Last Modified: 2010-05-18
If I have a string in PHP, for example

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

Question by:mawingho
LVL 143

Accepted Solution

Guy Hengel [angelIII / a3] earned 960 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";
{ // last 3 digits are not ok:
  echo "FAILURE";

Open in new window

LVL 48

Assisted Solution

hernst42 earned 80 total points
ID: 21791136
if (substr('CHH0A0606C3G', -3) == 'C3G') {

Assisted Solution

Fapiko earned 960 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:
function right($string, $length) {
   return substr($string, strlen($string) - $length);
// Thus this would return 'C3G':
echo right('CHH0A0606C3G', 3);

Open in new window


Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
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 and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

587 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