0

I have a string, consisting of: some numbers, a single letter, some numbers and letters.

For example: 987342j34kj3

I want to output something like:

$numbers = 987342
$letter = j
$restofit = 34kj3

Any idea how to do this with PHP? Can I use preg_match?

5
  • So, to clarify, your pattern is "some numbers, a letter, something which is letters and numbers"? Commented Dec 30, 2010 at 18:54
  • 1
    where is the letter k coming from? Is this consistent or is is that an arbitrary match? (How do you want it divided?) Commented Dec 30, 2010 at 18:55
  • @Brad: Hopefully a typo. Commented Dec 30, 2010 at 18:56
  • Sorry, yes! typo, well caught. corrected. Commented Dec 30, 2010 at 18:57
  • Was confused how you skipped over the first j for k, then back to it. @BoltClock has the answer for you. Commented Dec 30, 2010 at 18:59

1 Answer 1

4

No problem:

preg_match('/(\d+)([a-z])([a-z0-9]+)/', $string, $matches);

// First element of $matches is the entire matched string, ignore it
list(, $numbers, $letter, $restofit) = $matches;
Sign up to request clarification or add additional context in comments.

4 Comments

Except @David19801 skips over the first j and numbers 3&4. This will catch "987342", "k", then the rest of "34kj3".
I just caught the end delimiter not there. Thanks :) The k was a typo, corrected to j as you noticed correctly!
Remember if you need to match both uppercase and lowercase characters, slap an i modifier onto your regex.
Tried just now, works perfect, confirmed. Thanks a million. Needed the i too, but that was my fault not mentioning in the question. will tick once times up.

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.