0

I need to find all numbers in a string up until (but not including) anything that is not a number. If a number occours later on (after an occourance of a non-number-character) then it shouldn't be included either. I am trying with PHP's command preg_replace.

This question helped me to write the following pattern:

.+?(?=[^0-9])

Which though doesn't work in:

preg_replace("/.+?(?=[^0-9])/", "", $entry); 

where $entry is my string to search in.

As an example, I could have the following strings:

  • 001Aa.bc
  • 002a
  • 003a4/.
  • 004a(4)
  • 005 (4).string-d
  • 006-34

from which I want to have:

  • 001
  • 002
  • 003
  • 004
  • 005
  • 006

My pattern seems to work in test-sites, like http://gskinner.com/RegExr/. Is my use of the PHP command wrong?

Community
  • 1
  • 1
Steeven
  • 4,057
  • 8
  • 38
  • 68
  • Why don't you just match for numbers? The assertion seems needlessly complex. Or is this part of a bigger regex? – mario Mar 13 '13 at 16:15
  • `\d+` isn't ok good enough for you? – Michael Malinovskij Mar 13 '13 at 16:18
  • 1
    `\d+` will grab more than the numbers at the beginning. – Sturm Mar 13 '13 at 16:20
  • @mario, I don't follow you. I need to get the beginning numbers of the strings just as described. If there's an easy way, please tell me. – Steeven Mar 13 '13 at 16:30
  • None of these suggestions addresses the *question as asked* - only the OP would benefit from them. This is why it is important to answer the general question as asked that will be searched for by everyone else with a variety of legitimate motivations that are not a concern, rather than trying to find a workaround or alternative (as correct as they may be) for the OP's issue specifically. – Peter Kionga-Kamau Jun 06 '22 at 21:03

1 Answers1

1

Use preg_match()

preg_match(/^(\d)+/, $search_me, $save_string_to_me);

While it's rubular and not explicitly php, I imagine something this simple works the same: http://rubular.com/r/aqZhNC4nJq

Sturm
  • 4,105
  • 3
  • 24
  • 39