首页 > 解决方案 > 调用其他地方没有的变量

问题描述

在下面的代码中,从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>.

标签: php

解决方案


preg_replace_callback()函数是以这种方式编写的,它使用定义明确的参数调用该函数。请参阅此功能的手册:

将调用并传递主题字符串中匹配元素数组的回调。回调应该返回替换字符串。这是回调签名:

handler ( array $matches ) : string

因此,您的函数acronym()将从正则表达式中获取一个包含匹配项的数组。请记住,您不是acronym()自己调用该函数,该函数preg_replace_callback()会为您执行此操作(使用文档中定义的参数)。


推荐阅读