David19801
David19801

Reputation: 11448

regex to match 3 parts from a given string

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?

Upvotes: 3

Views: 165

Answers (2)

Toto
Toto

Reputation: 91385

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
$

Upvotes: 1

codaddict
codaddict

Reputation: 455020

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

Upvotes: 0

Related Questions