开发者

Regex on PHP not working correctly [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopen开发者_开发问答ed, visit the help center for guidance. Closed 11 years ago.
$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]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜