tags:

views:

30

answers:

2

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,"....

+1  A: 
$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.

Emil Vikström
Warning: preg_replace(): Unknown modifier 'g'
Sarfraz
That gets him half-way - also need to shorten the text to strip out the stuff between "Second World War[1]" and 'in a state of "total war"'.
Dominic Rodger
I agree with Dominic. Also, it would be better to do the preg_replace on the shortened paragraph instead on the whole text.
Ben
@Ben - you can't detect what the shortened paragraph should be until you've searched the whole text.
Dominic Rodger
A: 

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.

alex
Might want `str_ireplace` rather than `str_replace`, for the case-insensitive goodness (http://php.net/str_ireplace).
Dominic Rodger
i need to display only 250 words and all that should could cover maximum possible matches....
Ramesh
@Dominic Yep! You are correct
alex