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.

2
  • he didn't say it has to be with ereg_* :P Commented Jul 22, 2012 at 1:49
  • do you need to replace only the 12-th char or everything after it ? Commented Jul 22, 2012 at 1:56

3 Answers 3

2

Why not use substr()?

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

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

Sign up to request clarification or add additional context in comments.

4 Comments

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, 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.
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, 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.
0

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

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

1 Comment

isn't \w\d redundant? I believe \w includes digits. Thus the following pattern should do as good: /^(\w{12})\d+$/
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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.