Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>My thought process:</p> <ol> <li>Create a results array that supports non-unique name/value pairs (PHP supports this in its standard <code>array</code> object)</li> <li>Loop through each search term and find its character starting position in the search text</li> <li>Add an item to the results array that stores this character position it has just found with the actual search term as the key</li> <li>When you've found all the search terms, sort the array ascending by value (the character position of the search term)</li> <li>Now, the search results will be in order that they were found in the search text</li> <li>Loop through the results array and use the specified word padding to get words on each side of the search term while also keeping track of the word count in a separate name/value pair</li> </ol> <p>Pseudocode, or my best attempt at it:</p> <pre><code>function string GetSearchExcerpt(searchText, searchTerms, wordPadding = 0, searchLimit = 3) { results = new array() startIndex = 0 foreach (searchTerm in searchTerms) { charIndex = searchText.FindByIndex(searchTerms, startIndex) // finds 1st position of searchTerm starting at startIndex results.Add(searchTerm, charIndex) startIndex = charIndex + 1 } results = results.SortByValue() lastSearchTerm = "" searchTermCount = new array() outputText = "" foreach (searchTerm =&gt; charIndex in results) { searchTermCount[searchTerm]++ if (searchTermCount[searchTerm] &lt;= searchLimit) { // WordPadding is a simple function that moves left or right a given number of words starting at a specified character index and returns those words outputText += "..." + WordPadding(-wordPadding, charIndex) + "&lt;strong&gt;" + searchTerm + "&lt;/strong&gt;" + WordPadding(wordPadding, charIndex) } } return outputText } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload