开发者

Search Result displaying-like google php

开发者 https://www.devze.com 2023-01-01 01:34 出处:网络
i have an paragraph and user will search inside that and if the search term has 3 matches inside but all are in 3 different places

i have an paragraph and user will search inside that and if the search term has 3 matches inside but all are in 3 different places

ex

World War II, or the Second World War[1] (often abbreviated WWII or WW2), was a global military conflict lasting from 1939 to 1945 which involved most of the world's nations, including all of the great powers, organised into two opposing military alliances: the Allies and the Axis. It was the most widespread war in history, with more than 100 million military personnel mobilised. In a state of "total war," the major participants placed their entire economic, industrial, and scientific capabilities at the service of the 开发者_开发知识库war effort, erasing the distinction between civilian and military resources. Marked by significant action against civilians, including the Holocaust and the only use of nuclear weapons in warfare, it was the deadliest conflict in human history,[2] with over seventy million casualties.

i have to search "war" so that it should display like

World War II, or the Second World War[1].....In a state of "totalwar,"....


$text = 'World War II, or the Second World W...';
$text = preg_replace('/war/ig', '<strong>$0</strong>', $text);

You can read more about preg_replace and regular expressions in the manual.


I don't have a PHP solution, but I suggest you could do this on the client side. This means you can cache any output server side and save some cycles :)

Disclaimer: This is my own project.

Check out searchTermsHighlight, a jQuery plugin. Demo. Modify the source so instead of checking the referrer, it checks the query parameters.

Alternatively, if you want to do it in PHP, you will use stri_replace() most probably like so. You can avoid regex because you are searching for straight matches and don't need any of the intelligence that regex offers.

$searchTerms = array('war');

foreach($searchTerms as $term) {

    $content = stri_replace($term, '<span class="highlight">' . $term . '</strong>', $content);

}

stri_replace() as noted in the comments by Dominic Rodger.

0

精彩评论

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