【发布时间】:2020-11-25 12:18:35
【问题描述】:
我正在使用Simple HTML Dom Parser 更正我的输出中的一些链接以达到良好效果,但在通过 Ajax 调用内容时发现了一些奇怪的行为。我在 WordPress 网站上使用解析器,因此将 $content 变量输入以下函数:
function add_trailing_slash( $content ) {
$content = str_get_html( $content );
if( $content ):
foreach( $content->find('a') as $a ):
if( isset( $a->href ) && '' !== $a->href && '#' !== $a->href ):
// replace http with https on all link hrefs
$a->href = str_replace('http:', 'https:', $a->href);
// checks if link lacks trailing slash and appends it if no extension (file)
$ext = pathinfo( $a->href, PATHINFO_EXTENSION );
if( '/' !== substr( $a->href, -1 ) && ! $ext ) $a->href = $a->href . '/';
endif;
endforeach;
endif;
return $content;
}
当使用add_filter( 'the_content', 'add_trailing_slash' ) 添加到the_content 过滤器时效果很好,即使像return add_trailing_slash( $output ) 一样直接调用但是,当我通过Ajax 调用相同的函数时,我得到一个“成功”响应,但它完全是空的。更奇怪的是,我发现如果我通过wpautop( $output ) 返回输出,它就会恢复正常。 wpautop (link) 本质上是一堆 preg_replace 函数,用 <p> 标签替换双换行符,所以我测试了通过 return preg_replace('<blah>', '', $content) 返回我的输出,它工作!
哦,我还测试了从上面的 add_trailing_slash() 函数中删除我的所有更改,但同样的问题仍然存在,所以我猜想与 str_get_html( $content ) 解析输入的方式有关,使其无法很好地与 Ajax 回调配合使用。但是为什么preg_replace 让它可以退货呢?
function add_trailing_slash( $content ) {
$content = str_get_html( $content );
return $content;
}
我想知道是否有其他人遇到过这个问题,我是否遗漏了一些东西并且这是预期的,或者这是否是一个错误?我可以留在我的 preg_replace 中,这似乎可以“解决”问题,但感觉就像是黑客攻击。
【问题讨论】:
标签: ajax wordpress parsing preg-replace domparser