2010-04-08 110 views
0

我有一長段從搜索查詢中回來的文本。 我想顯示文本的片段,而不是整個內容,並突出顯示片段中的搜索查詢。 我意識到決定要分片的文本的哪一部分可能會變得複雜,並且我希望得到關於如何做到這一點的任何想法?在php中生成代碼片段

謝謝!

+0

是否有任何HTML字符,或者它是純文本? – 2010-04-08 22:02:06

+0

*(相關)* http://stackoverflow.com/search?q=highlight+text+php – Gordon 2010-04-08 22:02:30

回答

1

例如

$text = " 
I have a long chunk of text that came back from a search query. I'd like to display a 
snippet of the text, not the entire thing, and highlight the search query within the 
snippet. I realize that decided what part of the text to slice can be complicated, and 
I was hoping for any ideas on how do to this? 
"; 

$query = "the text"; 

preg_match("~\b.{0,20}$query.{0,20}\b~", $text, $m); 
echo str_replace($query, "<strong>$query</strong>", $m[0]);