Paul Williams
Paul Williams

Reputation: 1598

preg_split and multiple patterns

I have following bit of php code using regular expressions:

$result_from_pull = "T601092";

if(preg_match("/^[A-Za-z0-9]{2,6}[0-9]{1,3}$/", $result_from_pull)) {
    echo "We found a \"valid\" UFS key.";
}

What I'm trying to do is split the string into two parts. The first part would match the beginning of the pattern, [A-Za-z0-9]{2,6}, while the second part would match the tail end of the pattern, [0-9]{1,3}.

How do I use preg_split to accomplish this? Can it be done on one preg_split or should I be using two or another function altogether?

Upvotes: 3

Views: 1916

Answers (3)

hwnd
hwnd

Reputation: 70732

Using preg_split() you can achieve this using a reluctant quantifier with your {n,m} repetition, the \K escape sequence and a Positive Lookahead.

$results = preg_split('/^[a-z0-9]{2,6}?\K(?=[0-9]{1,3}$)/i', $string);
print_r($results);

Live Demo ( or see a working demo )

Upvotes: 5

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

preg_split is the wrong function for this. Use capture groups.

if(preg_match("/^([A-Za-z0-9]{2,6})([0-9]{1,3})$/", $result_from_pull, $matches)) {
    echo "We found a \"valid\" UFS key.";
    var_dump($matches);
    // you should see the first part in $matches[1], and the second in $matches[2]
}

Upvotes: 3

Braj
Braj

Reputation: 46841

Get the matched group from index 1 and 2

^([A-Za-z0-9]{2,6})([0-9]{1,3})$

DEMO

sample code:

$re = "/^([A-Za-z0-9]{2,6})([0-9]{1,3})$/";
$str = "T601092";

preg_match($re, $str, $matches);

Upvotes: 2

Related Questions