Skip to content

Instantly share code, notes, and snippets.

/SearchPage.php

Created Nov 27, 2013
Embed
What would you like to do?
Exemplo de como pesquisar termos em arquivos
<?php
include_once "lib/SearchPage.php";
//Define as paginas a serem pesquisadas
$pages = array('contato.html', 'quem-somos.html');
//Instancia a classe SearchPage, e informa as páginas
$search = new SearchPage($pages);
//Informa o termo q ser pesquisado nas paginas
$search->setSearch('sites');
//Executa a pesquisa nos arquivos
$execute = $search->execute();
?>
<!doctype html>
<html lang="pt_BR">
<head>
<meta charset="UTF-8">
<title>Pesquisa</title>
</head>
<body>
<!-- Se não encontrar nenhum resultado-->
<?php if(!$execute) : ?>
<h1>Nenhum resultado encontrado</h1>
<?php else: ?>
<!-- Informa a quantidade itens retornados-->
<h1>Total de Resultados : <?php echo $search->getCount()?></h1>
<?php foreach($search->getResult() as $obj) : ?>
<h2><a href="<?php echo $obj->page?>"><?php echo $obj->title?></a></h2>
<?php echo substr( $obj->content, 0, 100)?>
<?php endforeach;?>
<?php endif?>
</body>
</html>
<?php
class SearchPage {
private $search;
private $pages;
private $result;
public function __construct(array $pages) {
$this->pages = $pages;
}
public function setSearch($search) {
$this->search = $search;
}
private function setResult($page, $content) {
$obj = new stdClass;
$obj->page = $page;
$obj->content = $content;
$obj->name = basename($page);
$name = explode('.', basename($page));
$obj->title = $name[0];
$this->result[] = $obj;
}
private function getFileContent($page) {
$content = file_get_contents($page);
$strip = trim(strip_tags($content));
$obj = new stdClass;
$obj->content = $content;
$obj->stripContent = $strip;
return $obj;
}
public function has($page) {
return file_exists($page);
}
public function execute() {
$result = false;
if ($this->search) {
foreach ($this->pages as $page) {
if ($this->has($page)) {
$obj = $this->getFileContent($page);
if (stristr($obj->stripContent, $this->search) == true) {
$this->setResult($page, $obj->content);
if (!$result) $result = true;
}
}
}
}
return $result;
}
public function getResult() {
return $this->result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment