放牧代码和思想
专注自然语言处理、机器学习算法
    This thing called love. Know I would've. Thrown it all away. Wouldn't hesitate.

Chapter 12: Manipulating User Input: The Filter System

这一章很短很简单,如果你需要手工的对输入信息进行格式化,那么向网站添加内容将是一个繁琐的工作。相反,如果想让网站上的文本内容看起来很漂亮,那么你需要懂得HTML— 但是大多数用户都不了解这一知识。对于我们中的那些熟悉HTML的人,如果在头脑风暴会议或者文章创作期间,不断的暂停,并向我们的文章中插入HTML标签,这也会令人头痛。段落标签、链接标签、换行标签。。。太烦了。幸好,Drupal提供了预制的程序,这就是过滤器,它使得数据输入更加方便和高效。过滤器执行文本处理,比如为URL添加链接,将换行符转化为<p> 和 <br />标签,甚至包括过滤有害的HTML。钩子hook_filter()负责创建过滤器和处理用户提交的数据。

当然,Drupal 过滤器可以创建链接,格式化你的内容,将文本转换为pirate-speak,但是它能够聪明到帮我们写日志么,或者至少能够把我们创造性火花碰撞出来么?当然,它可以做到这一点!让我们创建一个带有过滤器的模块,用来向日志条目中插入随机的句子。我们将启用这一模块,这样当你在编写文章中绞尽脑汁毫无灵感并需要一些火花时,你可以简单的键入[juice!],当你保存文章时,它将会被替换为一个随机生成的句子。如果你需要更多的智慧火花时,你可以在一个文章中多次插入[juice!]标签。

creativejuice.info

name = Creative Juice
description = "Adds a random sentence filter to content."
package = Pro Drupal Development
core = 7.x
files[] = creativejuice.module
php = 5.2

creativejuice.module

<?php
/**
* @file
* A silly module to assist whizbang novelists who are in a rut by providing a
* random sentence generator for their posts.
*/
/**
 * Implement hook_filter_info().
 */
function creativejuice_filter_info()
{
    $filters = array();
    $filters['creativejuice'] = array(
            'title' => t('Creative Juice filter'),
            'description' => t('Enables users to insert random sentences into their post'),
            'process callback' => '_creativejuice_filter_process',
            'tips callback' => '_creativejuice_filter_tips'
    );
    return $filters;
}
/**
 * Creativejuice filter process callback
 *
 * The actual filtering is performed here. The supplied text should be
 * returned, once any necessary substitutions have taken place.
 * 实际的过滤是在这里发生的,返回替代之后的内容
 */
function _creativejuice_filter_process($text, $filter, $format)
{
    while(strpos($text, '[juice!]') !== FALSE)  // strpos — 查找字符串首次出现的位置
    {
        $sentence = creativejuice_sentence();
        $text = preg_replace('&\[juice!\]&', $sentence, $text, 1);
    }
    return $text;
}
/**
 * Generate a random sentence.
 * 生成一串随机句子数组
 */
function creativejuice_sentence()
{
    $beginnings = array();
    $beginnings[] = t('A majority of us believe');
    $beginnings[] = t('Generally speaking,');
    $beginnings[] = t('As times carry on');
    $beginnings[] = t('Barren in intellect,');
    $beginnings[] = t('Deficient in insight,');
    $beginnings[] = t('As blazing blue sky pours down torrents of light,');
    $beginnings[] = t('Aloof from the motley throng,');
    $beginnings[] = t('While crafting a new Drupal module,');
    $middles = array();
    $middles[] = t('life flowed in its accustomed stream');
    $middles[] = t('he ransacked the vocabulary');
    $middles[] = t('the grimaces and caperings of buffoonery sting');
    $middles[] = t('the mind freezes at the thought');
    $middles[] = t('reverting to another matter enables freedom');
    $middles[] = t('he lived as modestly as a hermit');
    $middles[] = t('the coder repeatedly invoked hooks');
    $ends = array();
    $ends[] = t('through the red tape of officialdom.');
    $ends[] = t('as it set anew in some fresh and appealing form.');
    $ends[] = t('supported by evidence.');
    $ends[] = t('as fatal as the fang of the most venomous snake.');
    $ends[] = t('as full of spirit as a gray squirrel.');
    $ends[] = t('as dumb as a fish.');
    $ends[] = t('like a damp-handed auctioneer.');
    $ends[] = t('like a bald ferret.');
    $ends[] = t('with a frozen, sharpened badger.');
    $ends[] = t('and achieve CMS nirvanna.');
    // For every phrase group, pick a random value.
    $sentence = array(
            $beginnings[mt_rand(0, count($beginnings) - 1)],    // mt_rand() 使用 Mersenne Twister 算法返回随机整数。
            $middles[mt_rand(0, count($middles) - 1)],
            $ends[mt_rand(0, count($ends) - 1)] 
    );
    // Take the three random values from the sentence groups,
    // implode them together, and return the sentence.
    // 用空格组合起来,然后返回
    return implode(' ', $sentence);
}
/**
 * Filter tips callback for creative juice filter.
 *
 * The tips callback allows filters to provide help text to users during the content
 * editing process. Short tips are provided on the content editing screen, while
 * long tips are provided on a separate linked page. Short tips are optional,
 * but long tips are highly recommended.
 */
function _creativejuice_filter_tips($filter, $format, $long = FALSE)
{
    if($long)
    {
        // Detailed explanation for http://example.com/?q=filter/tips page.
        return t('The Creative Juice filter is for those times when your
brain is incapable of being creative. These times come for everyone,
when even strong coffee and a barrel of jelly beans do not
create the desired effect. When that happens, you can simply enter
the [juice!] tag into your posts...');
    }
    else
    {
        // Short explanation for underneath a post's textarea.
        return t('Insert a random sentence into your post with the [juice!] tag.');
    }
}

测试效果,我们写一点什么:

保存之后被替换为:

这个功能其实没有特别大的作用吧,当然有些词语需要过滤的,你懂的。

知识共享许可协议 知识共享署名-非商业性使用-相同方式共享码农场 » Chapter 12: Manipulating User Input: The Filter System

评论 欢迎留言

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

我的作品

HanLP自然语言处理包《自然语言处理入门》