preg_grep返回整个字符串而不是part

时间:2013-09-12 19:12:54

标签: php regex

运行以下代码

$mysqlquery = "SELECT `description` FROM `table`";

$sqlresourceid = mysql_query($mysqlquery);
$subject = mysql_fetch_row($sqlresourceid);
$regexisbn = '/(97(8|9))?\d{9}(\d|X)/i';

$pattern = '/.*/i';

$matches  = preg_grep ($regexisbn, $subject);

var_dump($matches);

但是这会返回以下内容

ISBN10: 0470945176 by Paul D. Kimmel Publisher: John Wiley & Sons Copyright year: © 2011

我只是想让它返回ISBN 0470945176,这是怎么回事?

2 个答案:

答案 0 :(得分:0)

因为这是preg_grep的作用:它过滤输入数组,删除不匹配的条目。然后匹配的条目保持不变。

您想尝试preg_matchpreg_replace

答案 1 :(得分:0)

如果您只需要获取正则表达式的匹配部分,请尝试以下操作:

$str = 'ISBN10: 0470945176 by Paul D. Kimmel Publisher: John Wiley & Sons Copyright year: © 2011';
preg_match('/(?P<my_isbn>(97(8|9))?\d{9}(\d|X))/i', $str, $matches);
echo 'ISBN: <b>' . $matches['my_isbn'] . '</b>';

您的结果将是:

ISBN: 0470945176