Solved

Substring in PHP

Posted on 2008-06-15
3
791 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
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…
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…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

623 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