search - how to make snippet trimmed to a human readable sentence - php -
search - how to make snippet trimmed to a human readable sentence - php -
first give thanks helping me create nice search result query. hope friends can help me improve it.
here query
$searchresult = $mysql->query("select * pages pagecontent '%$searchterm%'"); if($searchresult->num_rows > 0) { while (($row = $searchresult->fetch_assoc()) !== null) { echo '<h3>' . $row["pagetitle"] . '</h1>'; $position = strpos($row["pagecontent"], $search); $snippet = substr($row["pagecontent"], $position - 200, $position + 200); echo $snippet . '<hr><br />'; } } else { echo "<p>sorry, can not find entry match query</p><br><br>"; }
what create snippet trim in such way not break word sentence readable .... , if possible create search term appear in bold. dear friends need help in doing so. give thanks in advance.
there's lot of room improvement, here's approach:
<?php echo trimsnippet("some really, really, reaaally long text don't care about, @ all.", "text", 30) . "\n"; function trimsnippet($text, $query, $max_length){ $position = strpos($text, $query); $snippet = substr($text, max($position - $max_length - 1, 0), strlen($query) + $max_length*2 + 1); echo "<$snippet>\n"; preg_match("/[^\w](?p<pre>.*)".$query."(?p<post>.*)[^\w]/", $snippet, $extracted); homecoming $extracted["pre"]."<strong>".$query."</strong>".$extracted["post"]; }
output: really, reaaally long text don't care about,
how utilize it:disregard first line (echo...), it's demo. place function anywhere in php uses it, , replace lines:
$position = strpos($row["pagecontent"], $search); $snippet = substr($row["pagecontent"], $position - 200, $position + 200)
with:
$snippet = trimsnippet($row["pagecontent"], $search, 200);
some improvemets create function: check $query appears in $text add ellipsis (...) origin or end of result control happens when $query near origin , end (and avoid adding ellipsis in case) sanitize $query (and $text also) cannot contain "regex syntax" mess regex pattern. php search mysqli code-snippets
Comments
Post a Comment