开发者

Bold some words in a string and remove some unbold words

I am creating a search engine. Currently, my script bolds the matching words from the keyword. But some keywords are too long, like the results for shah rukh khan:

25216d1235653089 shahrukh khan s wallpaper shah rukh actor

As you see, the above keyword is too long. So, I need it to be like:

shahrukh khan s wallpaper

or

shah ruk开发者_如何学编程h actor


Currently, I am using the following code, but it requires a space before and after the bold tags. So, if the 1st word is bold, it displays the whole keyword.

if(strlen($img_keyword)>30){
    $img_keyword = preg_replace('/(.*?) <b>(.*?)<\/b> (.*?)/us',
      " <b>$2</b> ",
      $img_keyword);
}

Is there a way to do/fix this?


Well, as far as I can see, you don't need the spaces in front and after the bold text, so why don't you just remove the space, add a start anchor at the beginning and an end anchor at the end of the pattern? Like this:

$img_keyword = preg_replace('/^(.*?)<b>(.*?)<\/b>(.*?)$/us'," <b>$2</b> ",$img_keyword);


After Franz's help, I edited my code as I mentioned below.

 $img_keyword = boldText($query, $img_keyword);
 if(strlen($img_keyword)>30){
 $img_keyword = preg_replace('/^(.*?)<b>(.*?)<\/b>(.*?)/u',"<b> $2 </b>",$img_keyword);
     }
if(strlen($img_keyword)>30){
$img_keyword = preg_replace('/<\/b>(.*?)<b>/x'," ",$img_keyword);
   }
if(strlen($img_keyword)>30){
$img_keyword = preg_replace('/<\/b>(.*?)$|(.*?)<b>$/x',"</b> ",$img_keyword);
 }

If the keywords is

kajol shah rukh vogue india blumarine

the result is

shah rukh


If the keyword is

p 18 mFEk4J448M labelsadt 0%2Clanguage en%2Cposttag feroz khan%2Cposttag khan died on 27 april%2Cposttag is no more%2Cposttag the style icon of bollywood

the result is

khan khan


Is there a way to keep one or two unbold words and remove others?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜