【问题标题】:How to find and add bold a string in a paragraph?如何在段落中查找并添加粗体字符串?
【发布时间】:2011-08-11 01:10:47
【问题描述】:

我正在为我的网站创建搜索脚本。但我想italic 每个搜索结果描述中的匹配词。我使用的脚本在PHP 中,描述段落有变量$search_desc。目前我正在使用str_ireplace() 函数来实现我的目标。 但我觉得我的目标太远了!这是函数

echo str_ireplace($search_query,"<i>".$search_query."</i>",$search_desc);

但问题是,如果搜索查询是search,例如搜索结果的描述是,

这是搜索演示的描述。

所以将italic属性添加到它显示的匹配词后的描述

这是搜索演示的描述。

所以你可以看到问题很大。因为原始描述被编辑了!所以有人对我的问题有任何想法吗?请告诉我!

【问题讨论】:

标签: php html search replace


【解决方案1】:

我认为您可以使用 javascript 轻松实现您的目标。试试这个:

1) 包含以下代码:

<style>
<!-- 
    SPAN.searchword { font-style:italic; }
    // -->
</style>
<script type="text/javascript">

function stripVowelAccent(str)
{
    var rExps=[ /[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
        /[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
        /[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
        /[\xD2-\xD4]/g, /[\xF2-\xF4]/g,
        /[\xD9-\xDB]/g, /[\xF9-\xFB]/g ];

    var repChar=['A','a','E','e','I','i','O','o','U','u'];

    for(var i=0; i<rExps.length; ++i)
        str=str.replace(rExps[i],repChar[i]);

    return str;
}

/* Modification of */
/* http://www.kryogenix.org/code/browser/searchhi/ */
/* See: */
/*   http://www.tedpavlic.com/post_highlighting_search_results_with_ted_searchhi_javascript.php */    
/*   http://www.tedpavlic.com/post_inpage_highlighting_example.php */
/* for additional modifications of this base code. */
function highlightWord(node,word,doc) {
     doc = typeof(doc) != 'undefined' ? doc : document;
    // Iterate into this nodes childNodes
    if (node.hasChildNodes) {
        var hi_cn;
        for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
            highlightWord(node.childNodes[hi_cn],word,doc);
        }
    }

    // And do this node itself
    if (node.nodeType == 3) { // text node
        tempNodeVal = stripVowelAccent(node.nodeValue.toLowerCase());
        tempWordVal = stripVowelAccent(word.toLowerCase());
        if (tempNodeVal.indexOf(tempWordVal) != -1) {
            pn = node.parentNode;
            if (pn.className != "searchword") {
                // word has not already been highlighted!
                nv = node.nodeValue;
                ni = tempNodeVal.indexOf(tempWordVal);
                // Create a load of replacement nodes
                before = doc.createTextNode(nv.substr(0,ni));
                docWordVal = nv.substr(ni,word.length);
                after = doc.createTextNode(nv.substr(ni+word.length));
                hiwordtext = doc.createTextNode(docWordVal);
                hiword = doc.createElement("span");
                hiword.className = "searchword";
                hiword.appendChild(hiwordtext);
                pn.insertBefore(before,node);
                pn.insertBefore(hiword,node);
                pn.insertBefore(after,node);
                pn.removeChild(node);
            }
        }
    }
}

function unhighlight(node) {
    // Iterate into this nodes childNodes
    if (node.hasChildNodes) {
        var hi_cn;
        for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
            unhighlight(node.childNodes[hi_cn]);
        }
    }

    // And do this node itself
    if (node.nodeType == 3) { // text node
        pn = node.parentNode;
        if( pn.className == "searchword" ) {
            prevSib = pn.previousSibling;
            nextSib = pn.nextSibling;
            nextSib.nodeValue = prevSib.nodeValue + node.nodeValue + nextSib.nodeValue;
            prevSib.nodeValue = '';
            node.nodeValue = '';
        }
    }
}

function localSearchHighlight(searchStr,doc) {
     doc = typeof(doc) != 'undefined' ? doc : document;
    if (!doc.createElement) return;
        if (searchStr == '') return;
    // Trim leading and trailing spaces after unescaping
    searchstr = unescape(searchStr).replace(/^\s+|\s+$/g, "");
    if( searchStr == '' ) return;
    phrases = searchStr.replace(/\+/g,' ').split(/\"/);
    // Use this next line if you would like to force the script to always
    // search for phrases. See below as well!!!
    //phrases = new Array(); phrases[0] = ''; phrases[1] = searchStr.replace(/\+/g,' ');
    for(p=0;p<phrases.length;p++) {
            phrases[p] = unescape(phrases[p]).replace(/^\s+|\s+$/g, "");
        if( phrases[p] == '' ) continue;
        if( p % 2 == 0 ) words = phrases[p].replace(/([+,()]|%(29|28)|\W+(AND|OR)\W+)/g,' ').split(/\s+/);
        else { words=Array(1); words[0] = phrases[p]; }
                for (w=0;w<words.length;w++) {
            if( words[w] == '' ) continue;
            highlightWord(doc.getElementsByTagName("body")[0],words[w],doc);
            }
    }
}

</script>

2) 调用函数

<script language="javascript">
window.onload=localSearchHighlight('search search');
</script>

Source

【讨论】:

  • 谢谢哥们,但我希望它是一个 PHP 代码。但无论如何我以后会使用它,这就是我投票的原因!
【解决方案2】:

我认为你想要使用的是 preg_replace。

http://php.net/manual/en/function.preg-replace.php

此功能允许您使用标记来搜索和替换找到的单词。这样的事情可能会起作用:

$string = "This is description for Search Demo";
$searchingFor = "/" . $searchQuery . "/i";
$replacePattern = "<i>$0<\/i>";
preg_replace($searchingFor, $replacePattern, $string);

此代码可能有错误,我只是快速将其拼凑在一起。但我认为这适合您的情况。

【讨论】:

  • 这是一个很好的解决方案。只有在使用斜线时才会出错。
【解决方案3】:
$string = "<p>Helllow world this is a string</p>";
str_replace('world','<b>world</b>',$string);

试试这个例子,它会正常工作

【讨论】:

  • 欢迎来到 SO。请您描述一下您的答案与问题的关系吗?谢谢。
  • 嗨。我是新来的。请指导我。你想要什么。&我能为你做什么? ;) 谢谢
猜你喜欢
  • 2014-10-22
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 2012-04-05
  • 1970-01-01
  • 2019-04-12
  • 1970-01-01
相关资源
最近更新 更多