12shadow12
12shadow12

Reputation: 317

Combining preg_match regex

I'm wondering if there is a way to somehow combine multiple regex statements into one? Maybe I could use an array, or can you purely do it with regex?

$reg    = '/[a-zA-Z0-9]{7}$/';
$reg_l  = '/[a-zA-Z0-9]{7}-lg$/';
$base   = 'Fz4vqVW'; // May also be Fz4vqVW-lg


if (preg_match($reg,$base) { //Just checks for a 7 long string
    echo '1';
} elseif (preg_match($reg_l,$base) { //Checks for 7 long string with -lg at the end
    echo '2';
} else {
    echo '0';
}

Upvotes: 1

Views: 362

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can simply count the number of items in the match result:

$base   = 'Fz4vqVW';
$m = [];

preg_match('~^[a-zA-Z0-9]{7}(-lg)?$~D', $base, $m);
echo count($m);

Upvotes: 0

hwnd
hwnd

Reputation: 70722

You can also modify your preg_match() call as follows:

$reg  = '/^[a-zA-Z0-9]{7}(-lg)?$/';

if (preg_match($reg, $base, $m))
    echo isset($m[1]) ? 2 : 1; else echo 0;

Upvotes: 1

anubhava
anubhava

Reputation: 785058

It can be combined in one regex with preg_replace_callback like this:

$reg = '/^(?:([a-zA-Z0-9]{7})(-lg)?|.*)$/';
$base   = 'Fz4vqVW'; // May also be Fz4vqVW-lg

echo preg_replace_callback($reg, function($m) { 
  if (isset($m[2])) return 2; elseif (isset($m[1])) return 1; else return 0; }, $base);

Example Code:

$arr=array('Fz4vqVW', 'Fz4vqVW-lg', 'foobar');
foreach ($arr as $a) {
    echo preg_replace_callback($reg, function($m) { if (isset($m[2])) return 2;
         elseif (isset($m[1])) return 1; else return 0; }, $a)."\n";
}

Output:

1
2
0

Upvotes: 1

Related Questions