首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP如何提取给定字符串的一部分?

PHP如何提取给定字符串的一部分?
EN

Stack Overflow用户
提问于 2010-10-08 12:02:45
回答 2查看 779关注 0票数 0

我正在为我的网站编写一个搜索引擎,需要提取带有给定关键字和搜索结果列表中的几个单词的文本块。我的结尾是这样的:

代码语言:javascript
复制
/**
 * This function return part of the original text with
 * the searched term and few words around the searched term
 * @param string $text Original text
 * @param string $word Searched term
 * @param int $maxChunks Number of chunks returned
 * @param int $wordsAround Number of words before and after searched term
 */
public static function searchTerm($text, $word=null, $maxChunks=3, $wordsAround=3) {
        $word = trim($word);
        if(empty($word)) {
            return NULL;
        }
        $words = explode(' ', $word); // extract single words from searched phrase
        $text  = strip_tags($text);  // clean up the text
        $whack = array(); // chunk buffer
        $cycle = 0; // successful matches counter
        foreach($words as $word) {
            $match = array();
            // there are named parameters 'pre', 'term' and 'pos'
            if(preg_match("/(?P\w+){0,$wordsAround} (?P$word) (?P\w+){0,$wordsAround}/", $text, $match)) {
                $cycle++;
                $whack[] = $match['pre'] . ' ' . $word . ' ' . $match['pos'];
                if($cycle == $maxChunks) break;
            }
        }
        return implode(' | ', $whack);
    }

这个函数不能工作,但是您可以看到基本的想法。欢迎您提出任何改进正则表达式的建议!

EN

回答 2

Stack Overflow用户

发布于 2010-10-08 12:19:53

如果不使用RegEx对输入进行净化,永远不要将用户内容注入到preg_quote模式中:

http://us3.php.net/manual/en/function.preg-quote.php

票数 1
EN

Stack Overflow用户

发布于 2010-10-08 12:54:18

为什么谷歌在这里没有最好的搜索引擎,我会看看他们的用具

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3890268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档