Hello, My name is Roi and I hope you will be able to help me - I want to create a code that search keyword texts. If it find the keyword it will print it and also print the line (lets say 15 note before and after the keyword)) where it find. for example, if I'm searching for the keyword "dog" in the text: "all the pets like food but dogs especially like to eat meat and more. In addition it important to know that dogs don't realy like to take a shower " the resualt will be: dog food but dogs especially like know that dogs don't realy I'll trully appreciate if you will add the right code for it Thank you in advance, Roi.
Okay, fine, here you go. It's not that easy with regular expression alone because of the possibility of overlap within your excerpt area. So I used a loop. // setup - change these to control how it works $str = "all the pets like food but dogs especially like to eat meat and more. In addition it important to know that dogs don't realy like to take a shower"; $search = 'dog'; $extra_chars = 15; // get rid of extra spaces and enclose with special characters to // facilitate excerpt generation at ends $str = '|' . trim(preg_replace('/\s+/', ' ', $str)) . '|'; // find end of string so we don't try to go past it $l = strlen($str) - 1; // loop through all occurrences of search target $extra_chars++; $i = 0; while (false !== ($pos = stripos($str, $search, $i))) { // define outer limits of excerpt $start_from = max($pos - $extra_chars, 0); $end_at = min($pos + $extra_chars, $l); $excerpt = substr($str, $start_from, $end_at - $start_from); // trim excerpt to word boundaries if (preg_match('/.*?[ \|](.*)[ \}]/', $excerpt, $matches)) echo "<p>" . str_replace($search, "<b>{$search}</b>", $matches[1]) . "</p>\n"; $i = $pos + 1; } PHP:
Hi Roi, Here is another suggestion: $search='dog'; $arr=array(); $s="all the pets like food but dogs especially like to eat meat and more. In addition it important to know that dogs don't realy like to take a shower "; preg_match_all("#([^\s]+\s)?([^\s]+\s)?{$search}\w*(\s[^\s]+)?(\s[^\s]+)?#i",$s,&$arr); echo (count($arr[0]))?implode(",<br /><br />",$arr[0]):"{$search} not found<br /><br />"; PHP: Regards, Nick