2011-07-22 109 views
-3
$productid = preg_match('/^.*?_/', $ProductPath); 
ShowProduct($productid); 

的问题是$的productid始终为1,从不改变不管$ productpath是什么,操作性的例子,如果productpath是/store/gst/prod_4它仍然等于1正则表达式在PHP工作不正常

+11

阅读的preg_match手册。 – cweiske

回答

3

也许这将帮助

preg_match('/^.*?_(\d+)/', $ProductPath, $matches); 
$productid = $matches[1]; 
0

与尝试:

preg_match('/^.*?_/', $ProductPath, $matches); 
$productid = (int) $matches[0]; 
0

如果你只想要得到的前几个字符,直到_下划线,你可以使用strtok代替:

$productid = strtok($ProductPath, "_"); 

(使用正则表达式才有意义,如果你(1)使用preg_match正确,(2)也验证这些前几个字符实际上是数字\d+。)

0
$productid = preg_match('/^.*?_/', $ProductPath, $match); 
print_r($match); 
2

的preg_match返回匹配的数目。这意味着你的模式匹配一​​次。如果你想得到结果,你需要使用preg_match的第三个参数。

See here the docs on php.net

0
$productid = preg_match('#(prod_)([0-9]+)#', $ProductPath); 
ShowProduct($productid[1]);