3

Example input:

hjkhwe5boijdfg

I need to split this into 3 variables as below:

  1. hjkhwe5 (any length, always ends in some number (can be any number))
  2. b (always a single letter, can be any letter)
  3. oijdfg (everything remaining at the end, numbers or letters in any combination)

I've got the PHP preg_match all setup but have no idea how to do this complex regex. Could someone give me a hand?

2 Answers 2

1

Have a try with:

$str = 'hjkhwe5boijdfg';
preg_match("/^([a-z]+\d+)([a-z])(.*)$/", $str, $m);
print_r($m);

output:

Array
(
    [0] => hjkhwe5boijdfg
    [1] => hjkhwe5
    [2] => b
    [3] => oijdfg
)

Explanation:

^           : begining of line
  (         : 1rst group
    [a-z]+  : 1 or more letters
    \d+     : followed by 1 or more digit
  )         : end of group 1
  (         : 2nd group
    [a-z]   : 1 letter
  )         : end group 2
  (         : 3rd group
    .*      : any number of any char
  )         : end group 3
$
Sign up to request clarification or add additional context in comments.

1 Comment

Coda was faster, but that explanation just nailed it. I now understand regex! Thank you :)
0

You can use preg_match as:

$str = 'hjkhwe5boijdfg';
if(preg_match('/^(\D*\d+)(\w)(.*)$/',$str,$m)) {
        // $m[1] has part 1, $m[2] has part 2 and $m[3] has part 3.
}

See it

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.