Skip to content
Advertisement

Bolding a keyword if found in a string

<?php
$keywords1 = array("stack","stack overflow");
$keywords2 = array("stack overflow","stack");
$str1 = "stack overflow";
$str2 = "stack overflow";
foreach($keywords1 as $kw){
    if (preg_match("~b$kwb~i", $str1)) {
        $str1 = str_replace($kw,'<b>'.$kw.'</b>',$str1);
         }
}
foreach($keywords2 as $kw){
    if (preg_match("~b$kwb~i", $str2)) {
        $str2 = str_replace($kw,'<b>'.$kw.'</b>',$str2);
         }
}
echo $str1;
echo "<br>";
echo $str2;

?>

Greetings, Actually I want to bold a keyword if it is found in a string. I am using php preg_match() method for this purpose. My keywords are stored in an array and by iterating through each keyword I match it with my string and then bold it. I am facing a problem here. Both of the above strings are giving me different outputs. str1 is giving me stack overflow while str2 is giving me stack overflow. But for both cases both of the words should be bold. Please give me the solution to solve this problem.

I have this issue on https://www.paraphraser.site/

Advertisement

Answer

See below Example code for Reference, you can do as per given examples:

preg_replace("/w*?$kww*/i", "<b>$0</b>", $str1)

w*? matches any word characters before the keyword (as least as possible) and w* any word characters after the keyword.

And I recommend you to use preg_quote to escape the keyword:

preg_replace("/w*?".preg_quote($kw)."w*/i", "<b>$0</b>", $str1)

For Unicode support, use the u flag and p{L} instead of w:

preg_replace("/p{L}*?".preg_quote($kw)."p{L}*/ui", "<b>$0</b>", $str1)

For your code you can do it Like below:

        $keywords1 = array("stack","stack overflow");
    $keywords2 = array("stack overflow","stack");
    $str1 = "stack overflow";
    $str2 = "stack overflow";
    usort($keywords1, function($a, $b){
    return strlen($a) < strlen($b);
    });
    usort($keywords2, function($a, $b){
    return strlen($a) < strlen($b);
    });
    foreach($keywords1 as $kw){
        if (preg_match("~b$kwb~i", $str1)) {
            $str1 = preg_replace("/b$kwb/", "<b>$0</b>", $str1);
            // $str1 = str_replace($kw,'<b>'.$kw.'</b>',$str1);
            }
    }
    foreach($keywords2 as $kw){
        if (preg_match("~b$kwb~i", $str2)) {
            // $str2 = str_replace($kw,'<b>'.$kw.'</b>',$str2);
            $str2 = preg_replace("/b$kwb/", "<b>$0</b>", $str2);
            }
    }
    echo $str1;
    echo "<br>";
    echo $str2;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement