以下代码段从显示为预告片的节点的 body 字段中删除所有标签。也就是说,它从body字段创建的原始teaser中剥离标签,注意不要从CCK等模块添加到teaser的额外字段中剥离标签。
第 1 步(共 1 步)
在您的 template.php 中,将以下内容添加到节点预处理函数中:
function THEME_preprocess_node(&$vars, $hook) {
// Strip tags from teaser
if ($vars['teaser']) {
// $coreteaser is the teaser without extra cck fields
$coreteaser = $vars['node']->content['body']['#value'];
// Make sure there is content to strip tags from
if ($coreteaser) {
$teaser = $vars['content'];
// Calculate position of $coreteaser in $teaser
$start = strpos($teaser, $coreteaser);
// Calculate length of core teaser with tags
$length = strlen($coreteaser);
// Strip tags from $coreteaser
$replacement = strip_tags($coreteaser);
// Replace corresponding part of $teaser with stripped $coreteaser
$vars['content'] = substr_replace($teaser, $replacement, $start, $length);
}
}
}
笔记
请务必将上面的 THEME 替换为您的主题名称。
在()函数strip_tags的可扩展到允许某些标签
注释
使用此 strip_only 函数有选择地删除 html 标签
道具 sheena_d 将我指向此页面和http://php.net/manual/en/function.strip-tags.php。通过将来自 php.net 页面的 Steve 的 strip_only 函数与此页面上的代码相结合,您可以有选择地从预告片中删除 html 标签。我需要它来删除 img 标签。我在时事通讯的右边框上有一个又长又窄的图形。预告片副本的时间要长得多,并最终与除了它原本打算使用的预告片之外的其他预告片接壤。这是像魅力一样工作的代码:
登录或注册以发表评论
如何使用?
请给我一个示例,如何使用此功能仅去除粗体和斜体标签?
登录或注册以发表评论
仅去除粗体和斜体标签
要去除粗体和斜体标签,只需更改 $replacement 字符串,使其与此相同:
b 和 i 标签包含 bin 只是为了防止用户仍然使用粗体和斜体的旧方法。
登录或注册以发表评论
我试过这个
我用 Adaptive 主题尝试过这个,但似乎我错过了一些东西,因为我似乎无法让它工作。
我正在使用内联图像,因为我的内容是一个节点而不是视图中的一个字段,而且我还没有使用 CKEditor。
任何我可能会出错的想法。
登录或注册以发表评论
同样的事情(但主题不同)
我也不明白为什么它对我不起作用。我不使用任何编辑器。还尝试使用 Garland 主题和正常的默认页面内容类型。
最后用这个代码删除了 img 标签,我的朋友告诉我尝试:
print preg_replace('#<img[^>]+>#i', '', $node->content['body']['#value']);
将其放入 node.tpl.php 文件中。
登录或注册以发表评论
D7版
登录或注册以发表评论
这对我有用
这对我来说适用于 D7 和 Bartik 主题,但我必须通过在 strip_only 函数的 for_each 行之后添加这一行来硬编码我想要剥离的标签 img:
$str = preg_replace('/<img[^>]*>/', '', $str);
将 img 添加到函数调用中的标签列表不起作用,并且它也没有删除它应该删除的 iframe 标签。我还必须将 $vars 更改为 $variables。我不确定 strip-only 功能有什么问题,但其他一切似乎都没问题。
我还决定去掉 div 标签和里面的任何东西,因为我在文章中使用它们的唯一一次是浮动带有标题的图像。最好检查 div 中的 img,然后才匹配结束的 div 标签,但这可以满足我现在的需要。
$str = preg_replace('/<div.*?<\/div>/', '', $str); /*Remove anything between the nearest opening and closing <div> tags. *Doesn't handle nested divs!* */
登录或注册以发表评论
img 是自封闭的
img 标签在这里不起作用的原因是 strip_only 仅替换标签及其关闭计数器部分。img-tag 具有以下结构:,但 strip_only 搜索和。
<tag />
<tag>
</tag>
此外,对于多个标签,我只得到了标签之间没有空格的结果,即对我不起作用,但确实如此。
'<iframe> <div>'
'<iframe><div>'
登录或注册以发表评论
保持样式标签
如果您只想保留某些标签并去除其余标签,即。保留 a、img、strong 等,然后您可以更改:
strip_tags($coreteaser)
到...
strip_tags($coreteaser, '<a> <img> <strong> <em> <b> <i> <span> <div> <h1> <h2>')
该函数可以使用两个参数输入,第一部分定义要剥离的字符串,第二部分是您想要从条纹中排除的标签,这样您仍然可以保持样式。
登录或注册以发表评论
来自 https://www.drupal.org/node/659458