如何在段落中查找并添加粗体字符串?

发布于 2024-11-02 14:34:56 字数 576 浏览 1 评论 0原文

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

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

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

这是搜索演示的说明。

因此,将 italic 属性添加到它显示的匹配单词后的描述

这是搜索演示的说明。

所以你可以看到问题很大。因为原来的描述被编辑了!那么有人对我的问题有什么想法吗?如果您确实请告诉我!

I have being creating a Search Script for my site. But I wanna italic the matched words in the Description of every search result. The script I'm using is in PHP and the Description paragraph has variable $search_desc. Currently I'm using str_ireplace() function to achieve my goal. But I think my goal is too far away! Here is the function

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

But the problem is that if the search query is search and for the example the Description of a search result is,

This is description for Search Demo.

So the Description after adding italic property to the matched word it shows

This is description for search Demo.

So you can see the problem is big. Because the original Description gets edited! So anyone have got any ideas for my problem? Please if you do let me know!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

乖乖哒 2024-11-09 14:34:56

我认为你想要使用的是 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);

这段代码可能有错误,我只是快速地将它放在一起。但我认为这对于您的情况来说是正确的想法。

I think what you want to use is preg_replace.

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

This function allows you to search and replace using a token for the word that was found. Something like this might work:

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

This code might have errors, I just threw it together quickly. But I think this is the right idea for your situation.

℡Ms空城旧梦 2024-11-09 14:34:56

我认为你可以使用 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

I think you can easily achieve your goal using javascript. Try this:

1) Include the following code:

<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) Call the function

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

Source

萌无敌 2024-11-09 14:34:56
$string = "<p>Helllow world this is a string</p>";
str_replace('world','<b>world</b>',$string);

试试这个例子,它会工作得很好

$string = "<p>Helllow world this is a string</p>";
str_replace('world','<b>world</b>',$string);

Try This example it will work fine

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文