在下面的代码中,在https://github.com/Apress/beginning-php-and-mysql-5e/blob/master/9-1.php中,如果调用acronym函数而没有提到$matches,那么在acronym的定义中,$matches是如何从没有链接到任何东西的,而是在isset($acronym[$matches[1]]))中使用的呢?isset首先是如何知道$matches是什么?
下面是代码,我已经测试过它是否有效。我只是不能继续使用任意的术语:$matches及其使用。
// This function will add the acronym's long form
// directly after any acronyms found in $matches
function acronym($matches) {
$acronyms = array(
'WWW' => 'World Wide Web',
'IRS' => 'Internal Revenue Service',
'PDF' => 'Portable Document Format');
if (isset($acronyms[$matches[1]]))
return $acronyms[$matches[1]] . " (" . $matches[1] . ")";
else
return $matches[1];
}
// The target text
$text = "The <acronym>IRS</acronym> offers tax forms in
<acronym>PDF</acronym> format on the <acronym>WWW</acronym>.";
// Add the acronyms' long forms to the target text
$newtext = preg_replace_callback("/<acronym>(.*)<\/acronym>/U", 'acronym',
$text);
print_r($newtext);产出如下:
The Internal Revenue Service (IRS) offers tax forms inPortable Document Format (PDF) format on the World Wide Web (WWW).
提示:函数preg_replace_callback的输入是:
The <acronym>IRS</acronym> offers tax forms in <acronym>PDF</acronym> format on the <acronym>WWW</acronym>.
发布于 2020-01-11 15:36:32
preg_replace_callback()函数就是这样编写的,它用一个定义良好的参数调用该函数。请参阅此功能手册:
将在主题字符串中调用和传递匹配元素数组的回调。回调应该返回替换字符串。这是回调签名: 处理程序(数组$matches ):字符串
因此,您的函数acronym()将从regex获得一个带有匹配的数组。请记住,您不是单独调用acronym()函数,而是函数preg_replace_callback()为您调用(使用文档中定义的参数)。
https://stackoverflow.com/questions/59695817
复制相似问题