Preg Match Word

时间:2012-05-22 21:51:26

标签: php regex preg-match

我有这个字符串。

$string = 'product_posting_list_name_1';

我正在使用它来找到匹配但是找不到匹配。任何人都可以向我解释原因吗?我想匹配最后一个下划线和数字。

preg_match('/\bproduct_posting_list_name\b/', $string)

2 个答案:

答案 0 :(得分:4)

_下划线,is considered to be a word character里面您通过\b放置的边界,而不是边界本身。您的正则表达式正在寻找边界之间的完整单词,但边界发生在_1之后。

要匹配它,您不能在右侧使用边界。

$string = "product_posting_list_name_1";
// Replace the right-side \b with a [\d]+ to indicate 1 or more digits, followed by the \b boundary.
preg_match('/\bproduct_posting_list_name_[\d]+\b/', $string);

答案 1 :(得分:0)

不是正则表达式,但有效:

$string = 'product_posting_list_name_1';
if (strpos($string, 'product_posting_list_name') === 0) { echo 'found'; }