0

I have three situations, where I need to remove numbers characters.

STRING200, after preg_replace I expect STRING
STRING 100 TEST, after preg_replace I expect STRING 100 TEST
STRING 400, after preg_replace I expect STRING 400

I have tested the following combinations using preg_replace in PHP

/^(?:[0-9]+\s)*/
/[0-9]*$/
/^[a-zA-Z]+[0-9]*$

But without success, does anyone have any suggestions?

1
  • 1
    before/after 'string 100 test' and 'string 400' are the same. Commented Jul 21, 2017 at 17:44

1 Answer 1

1

You may match 1+ digits after a letter until a word boundary and remove them:

preg_replace('~[a-zA-Z]\K\d+\b~', '', $s)

See the regex demo.

Or if you need to match the whole string (see another demo):

preg_replace('~^[a-zA-Z]+\K\d+$~', '', $s)

Pattern details:

  • [a-zA-Z] - an ASCII letter
  • \K - match reset operator omitting the matched letter from the match value
  • \d+\b - 1 or more digits followed by the end of word boundary.

NOTE: If the match is expected at the end of the string, replace \b with $ (end of string anchor).

A PHP test:

$arr = ['STRING200','STRING 100 TEST','STRING 400'];
foreach ($arr as $s) {
   echo preg_replace('~[a-zA-Z]\K\d+\b~', '', $s) . PHP_EOL;    
}
// => [ STRING, STRING 100 TEST, STRING 400 ]
Sign up to request clarification or add additional context in comments.

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.