使用s9e \ TextFormatter的未定义变量$ parser

时间:2017-04-11 15:38:10

标签: php text-formatting

编辑:这不是关于未定义变量的一般性问题,而是关于此特定代码示例,该示例在不指定位置的情况下提取变量。

我正在尝试使用 s9e \ TextFormatter 设置标记为here的HTML白名单。

这是我的代码:

use s9e\TextFormatter\Configurator;

function htmlFormat( )
{
    $configurator = new Configurator;
    $configurator->plugins->load( 'HTMLElements' );

    $configurator->HTMLElements->allowElement( 'b' );
    $configurator->HTMLElements->allowAttribute( 'b', 'class' );
    $configurator->HTMLElements->allowElement( 'i' );

    // Get an instance of the parser and the renderer
    extract( $configurator->finalize() );

    $text = '<b>Bold</b> and <i>italic</i> are allowed, but only <b class="important">bold</b> can use the "class" attribute, not <i class="important">italic</i>.';
    $xml = $parser->parse( $text );
    $html = $renderer->render( $xml );
}

htmlFormat();

然而,变量$parser$renderer从未在该示例代码中定义。我不知道如何将它们集成到这段代码中,对吗?

1 个答案:

答案 0 :(得分:1)

这一行

extract( $configurator->finalize() );

定义那些变量。这是因为extract()将“将变量导入到数组的当前符号表中 1 (指the PHP documentation example可能会有所帮助了解这一点)。查看Configurator::finalize()的文档块:

/**
* Finalize this configuration and return all the relevant objects
*
* Options: (also see addHTMLRules() options)
*
*  - addHTML5Rules:    whether to call addHTML5Rules()
*  - finalizeParser:   callback executed after the parser is created (gets the parser as arg)
*  - finalizeRenderer: same with the renderer
*  - optimizeConfig:   whether to optimize the parser's config using references
*  - returnParser:     whether to return an instance of Parser in the "parser" key
*  - returnRenderer:   whether to return an instance of Renderer in the "renderer" key
*
* @param  array $options
* @return array One "parser" element and one "renderer" element unless specified otherwise
*/
     

2

最后两个选项( returnParser returnRenderer )默认为true。

尝试运行这些行(配置Configurator实例后):

extract( $configurator->finalize() );
echo 'typeof $parser: '.get_class($parser).'<br>';
echo 'typeof $renderer: '.get_class($renderer).'<br>';

这应该产生这样的文字:

  

typeof $ parser:s9e \ TextFormatter \ Parser

     

typeof $ renderer:s9e \ TextFormatter \ Renderers \ XSLT

1 <子> http://php.net/extract

2 <子> https://github.com/s9e/TextFormatter/blob/master/src/Configurator.php#L223