Developer
Developer

Reputation: 2895

PHP Regex get reverse number

i have this:

$pattern = 'dev/25{LASTNUMBER}/P/{YYYY}'
$var = 'dev/251/P/2014'

in this situation {LASTNUMBER} = 1 how to get this from $var

vars in pattern can by more always in {}

pattern can by different example :

 $pattern = '{LASTNUMBER}/aa/bb/P/{OtherVar}'

in this situation var will by 1/aa/bb/p/some and want get 1

I need get {LASTNUMBER} have pattern and have results

Ok maybe is not possible :) or very very hard

Upvotes: 0

Views: 107

Answers (3)

Pedro Lobito
Pedro Lobito

Reputation: 98921

You probably need this:

<?php
$pattern = 'dev/251/P/2014';
preg_match_all('%dev/25(.*?)/P/[\d]{4}%sim', $pattern, $match, PREG_PATTERN_ORDER);
$match = $match[1][0];
echo $match; // echo's 1
?>

Check it online

If you need to loop trough results you can use:

<?php
$pattern = <<< EOF
dev/251/P/2014
dev/252/P/2014
dev/253/P/2014
dev/254/P/2014
dev/255/P/2014
EOF;

preg_match_all('%dev/25(.*?)/P/[\d]{4}%sim', $pattern , $match, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($match[1]); $i++) {
    echo  $match[1][$i]; //echo's 12345
}
?>

Check in online

Upvotes: 0

domis86
domis86

Reputation: 1357

$parts = explode("/", $pattern);
if (isset($parts[1])) {
    return substr($parts[1], -1);
}

will be faster than regex :)

Upvotes: 1

Philipp
Philipp

Reputation: 15629

use a regex..

if (preg_match('~dev/25([0-9])/P/[0-9]{4}~', $var, $m)) {
    $lastnum = $m[1];
}

Upvotes: 3

Related Questions