0

I have that string : $text=70ac0f2e7247e9a658f71fe6362bf53

I want to replace all consecutive numbers by only the first number. For example I want to replace 70 by 7, 7247 by 7, 658 by 6 and so on.

I have this pattern : $pattern = '/[0-9]{2,}/'; but I don't know how I could build the $replacement and the preg_replace to make :

preg_replace ($pattern2,$replacement,$text3);

Thank you !

0

2 Answers 2

1

Turning my comment into an answer, you need to use a capturing group:

preg_replace('/([0-9])[0-9]*/', '$1', $text3);

or like what @chris85 said you may go with a match resetter \K:

preg_replace('/[0-9]\K[0-9]*/', '', $text3);
Sign up to request clarification or add additional context in comments.

Comments

0

It doesn't make any sense to replace an empty string with an empty string, so only perform a replacement if consecutive numbers are encountered.

  1. Match a sinle digit, then
  2. Forget that matched character, then
  3. Match one or more digits (and remove them)

Code: (Demo)

$text = '70ac0f2e7247e9a658f71fe6362bf53';

echo preg_replace('#\d\K\d+#', '', $text);
// 7ac0f2e7e9a6f7fe6bf5

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.