Recipe 24.13. Program: Site Search


You can use site-search.php, shown in Example 24-29, as a search engine for a small-to-medium-size, file-based site.

site-search.php

<?php class SiteSearch {     public $bodyRegex = '';     protected $seen = array();     public function searchDir($dir) {         // array to hold pages that match         $pages = array();         // array to hold directories to recurse into         $dirs = array();         // mark this directory as seen so we don't look in it again         $this->seen[realpath($dir)] = true;         try {             foreach (new RecursiveIteratorIterator(             new RecursiveDirectoryIterator($dir)) as $file) {                 if ($file->isFile() && $file->isReadable() &&                 (! isset($this->seen[$file->getPathname()]))) {                     // mark this as seen so we skip it                     // if we come to it again                     $this->seen[$file->getPathname()] = true;                     // load the contents of the file into $text                     $text = file_get_contents($file->getPathname());                     // if the search term is inside the body delimiters                     if (preg_match($this->bodyRegex,$text)) {                     // construct the relative URI of the file by removing                     // the document root from the full path                     $uri = substr_replace($file->getPathname(),'',0,strlen                     ($_SERVER['DOCUMENT_ROOT']));                     // if the page has a title, find it                     if (preg_match('#<title>(.*?)</title>#Sis',$text,$match)) {                         // and add the title and URI to $pages                         array_push($pages,array($uri,$match[1]));                     } else {                         // otherwise use the URI as the title                         array_push($pages,array($uri,$uri));                     }                 }                 }             }         } catch (Exception $e) {             // There was a problem opening the directory         }         return $pages;     } } // helper function to sort matched pages alphabetically by title function by_title($a,$b) {         return ($a[1] == $b[1]) ?                strcmp($a[0],$b[0]) :                ($a[1] > $b[1]); } // SiteSearch object to do the searching $search = new SiteSearch(); // array to hold the pages that match the search term $matching_pages = array(); // directories underneath the document root to search $search_dirs = array('sports','movies','food'); // regular expression to use in searching files. The "S" pattern // modifier tells the PCRE engine to "study" the regex for greater // efficiency. $search->bodyRegex = '#<body>(.*' . preg_quote($_REQUEST['term'],'#').                      '.*)</body>#Sis'; // add the files that match in each directory to $matching pages foreach ($search_dirs as $dir) {     $matching_pages = array_merge($matching_pages,                                   $search->searchDir($_SERVER['DOCUMENT_ROOT'].'/'.$dir)); } if (count($matching_pages)) {     // sort the matching pages by title     usort($matching_pages,'by_title');     print '<ul>';     // print out each title with a link to the page     foreach ($matching_pages as $k => $v) {         print sprintf('<li> <a href="%s">%s</a>',$v[0],$v[1]);     }     print '</ul>'; } else {     print 'No pages found.'; } ?>

The program looks for a search term (in $_REQUEST['term']) in all files within a specified set of directories under the document root. Those directories are set in $search_dirs. It also recurses into subdirectories and follows symbolic links but keeps track of which files and directories it has seen so that it doesn't get caught in an endless loop.

If any pages are found that contain the search term, it prints a list of links to those pages, alphabetically ordered by each page's title. If a page doesn't have a title (between the <title> and </title> tags), the page's relative URI from the document root is used.

The program looks for the search term between the <body> and </body> tags in each file. If you have a lot of text in your pages inside <body> tags that you want to exclude from the search, surround the text that should be searched with specific HTML comments and then modify $body_regex to look for those tags instead. Perhaps your page looks like what is shown in Example 24-30.

Sample HTML page

<body> // Some HTML for menus, headers, etc. <!-- search-start --> <h1>Aliens Invade Earth</h1> <h3>by H.G. Wells</h3> <p>Aliens invaded earth today. Uh Oh.</p> // More of the story <!-- search-end --> // Some HTML for footers, etc. </body>

To match the search term against just the title, author, and story inside the HTML comments, change $search->bodyRegex to what is shown in Example 24-31.

Corresponding regular expression

$search->bodyRegex = '#<!-- search-start -->(.*' . preg_quote($_REQUEST['term'],'#').               '.*)<!-- search-end -->#Sis';

If you don't want the search term to match text that's inside HTML or PHP tags in your pages, add a call to strip_tags( ) to the code that loads the contents of the file for searching, as shown in Example 24-32.

Stripping HTML and PHP tags

// load the contents of the file into $text $text= strip_tags(file_get_contents($file->getPathname()));




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net