2

I will like to replace any numeric character from the 12th position of variable $key with an empty string: $key variable has 12 characters + incremented numeric characters. For example:

IODN4YFK5XKV1
GYDN4YFK5XKV2
P3FU4YFK5XKV3

Bellow is my current line of php code:

$data = ereg_replace( "[0-9]+$", "", $_REQUEST['code'] );

Problem: If my $key = HXGE1SR9OWM428, the last 3 digits (428) will be removed but I'll like to remove only the digits as from the 12th position so that my result will be $data = HXGE1SR9OWM4.

John Conde
  • 217,595
  • 99
  • 455
  • 496

3 Answers3

2

Why not use substr()?

 $data = substr($_REQUEST['code'], 0, 12);

FYI, ereg_* is deprecated in the newer version of PHP

Mike Mackintosh
  • 13,917
  • 6
  • 60
  • 87
  • wow, did you even read the question? "I will like to replace any `numeric` character from the 12th position of variable $key with an empty string" your code will drop whatever after 12th position. – mask8 Jul 22 '12 at 02:04
  • @mask8, Yes I did, and he doesnt say he wants to replace it ONLY if it is numeric. He stated the 12th character is numeric. He also said that he wants to replace it. Not the same thing. – Mike Mackintosh Jul 22 '12 at 02:05
  • yes that's true. but since my code does what @EngineerDeclan wants, do you see why I'm getting down vote lol mine even followed he wanted ereg_replace or preg_replace ha – mask8 Jul 22 '12 at 02:10
  • @mask8, i hear ya. And it works, which is why I dont understand why you got downvoted. All i did was offer an alternative, heck, that's pretty much what substr was made for. I hate when people downvote and never say why. – Mike Mackintosh Jul 22 '12 at 02:12
0

You can do like this: *I'm using preg_replace instead.

$data = preg_replace( "/^([\w]{12})[0-9]+$/", "$1", $_REQUEST['code'] );
mask8
  • 3,560
  • 25
  • 34
  • isn't `\w\d` redundant? I believe `\w` includes digits. Thus the following pattern should do as good: `/^(\w{12})\d+$/` – Geo Dec 21 '12 at 20:11
0

Using deprecated ereg_* as shown in your question you would do:

$data = ereg_replace('^([A-Z0-9]{12})[0-9]+', '\1', $_REQUEST['code']);

If lower-case letters need to be included in the pattern, simply change ereg_replace to eregi_replace.

However, a better approach would be to use the preg_* functions group instead:

$data = preg_replace('/^(\w{12})\d+$/', '$1', $_REQUEST['code']);

Again, for lower-case letters, just add i at the end of the pattern, so it's '/^(\w{12})\d+$/i'

Geo
  • 12,666
  • 4
  • 40
  • 55