php - 调用其他地方没有的变量
问题描述
在下面的代码中,从PHP 和 mySQL 5e 开始,如果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>.
解决方案
该preg_replace_callback()
函数是以这种方式编写的,它使用定义明确的参数调用该函数。请参阅此功能的手册:
将调用并传递主题字符串中匹配元素数组的回调。回调应该返回替换字符串。这是回调签名:
handler ( array $matches ) : string
因此,您的函数acronym()
将从正则表达式中获取一个包含匹配项的数组。请记住,您不是acronym()
自己调用该函数,该函数preg_replace_callback()
会为您执行此操作(使用文档中定义的参数)。
推荐阅读
- ruby - 在 Ruby 中捕获“无法统计:没有这样的文件或目录”错误
- office-ui-fabric - 获取焦点上的文本字段的值
- html - 单独列中的标题和内容
- python - 无法 pip 安装异常包
- c++ - FFmpeg 解码和转换 RGB sws_scale 错误
- google-apps-script - 如何让共享 google 工作表的其他用户能够执行此时间戳脚本?
- swift - 无法使用“NSAttributedString”类型的参数列表调用“编码”
- python - 熊猫字典到json附加到文件
- sapui5 - 无法使用 SAPUI5 在表中调用 Collection 类型的属性
- python - 我可以将项目文件转换为可执行文件吗?