Regex on PHP not working correctly [closed]
$productid = preg_match('/^.*?_/', $ProductPath);
ShowProduct($productid);
The problem is $productid is always 1 and never changes no matter what the $productpath is, forinstance if productpath is /store/gst/prod_4
it still equals 1
maybe this will help
preg_match( '/^.*?_(\d+)/', $ProductPath, $matches );
$productid = $matches[1];
preg_match returns the number of matches. That means your pattern matches once. If you want to have the result you need to use the third parameter of preg_match.
See here the docs on php.net
Try with:
preg_match('/^.*?_/', $ProductPath, $matches);
$productid = (int) $matches[0];
If you only want to get the first few characters until the _
underscore, you can use strtok
instead:
$productid = strtok($ProductPath, "_");
(Using the regex only makes sense if you (1) use preg_match
correctly, (2) also verify that those first few characters are actually numbers \d+
.)
$productid = preg_match('/^.*?_/', $ProductPath, $match);
print_r($match);
$productid = preg_match('#(prod_)([0-9]+)#', $ProductPath);
ShowProduct($productid[1]);
精彩评论