2011-07-22 339 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]);