I need to bold a search term and its context (within a sentence).
Consider the string:
Lorem ipsum dolor sit amet. Consectetuer adipiscing elit.
You could split the string into "sentences" (split on a full stop (what about exclamation marks, question marks, ...)).
Then find the sentence with the matching word.
Then split that sentence into "words" and add some tags in two words before and after the matching word. Since you only have one sentence to work on, you'd include a check to make sure you didn't go out of bounds of the word array.
Then join the words back together, and join all the sentences back together.
Alternatively, you could use regex and preg_replace (although that may not be a road you want to go down, especially if you have an option such as splitting on plaintext - there's a quote that goes something like "You have a problem and you want to use regex for it. Now you have two problems."):
$string = preg_replace("/\\b(\\w+ +){0,2}$query( +\\w+){0,2}\\b/i",
'<strong>$0</strong>',
$string);
The regex works like this (backslashes are escaped above):
\b | match a word boundary (ie match whole words)
(\w+ +) | match a "word" followed by spaces (to separate it from the next word)
{0,2} | match 0 to 2 of these such words (it will match as many as possible
| up to 2)
$query | match the '$query' string
( +\w+) | regex for space (separating $query) followed by a word
{0,2} | match 0 to 2 of these words (as many as possible up to 2)
\b | match a word boundary (ie match whole words)
The /i
at the end means "case insensitive".
The replacement string, <strong>$0</strong>
, means to replace with all the matched words surrounded by the 'strong' tags.
The reason this works is that the regular expression does not allow a full stop to be matched. So it will grab up to 2 words either side of $query
but is forbidden from going over full stops.
There are the usual caveats (that you would have with any method you used) -- do you want the bolding to go over question marks? exclamation marks? Is an apostrophe allowed in a word? What will you do about non-full-stop punctuation between words? etc.
I'd recommend refining the above regex (if you want to use regex, that is) to:
\w+
to [\w']+
(escape your for PHP backslashes too)+
to something like [\s\-&,]+
(means "space", "-", "&", "," are allowed between words -- add more to your liking, but don't put "." in to prevent the bold-ing from going over full stops).Hope this helps
$str ="your whole string ";
if(isset($_POST['searchStr']))
{
$searchStr= $_POST['searchStr'];
$str= str_replace($searchStr,'<b>'. $searchStr.'</b>',$str);
}
echo "$str";
if you want a case -insensitive replacement use below function
str_ireplace() - Case-insensitive version of str_replace.