2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

phpでテキストファイル内を検索し、表示する

Last updated at Posted at 2020-01-10

検索はこんな簡単にできるんです!

php
<style>
#form{
position: fixed;
top: 0;
z-index: 50;
}
</style>
<?php
$SPLIT = "|-|-|-|-|-|";
if (isset($_POST["keyword"])){
$keyword = $_POST["keyword"];
?>
<div id="form">
<form method="POST" action="">
<input type="text" name="keyword" placeholder="ここに検索ワードを入力" value="<?php echo $keyword ?>">
<input type="submit" value="検索">
</div>
</div>
<?php
$kekka = 0;
$data = file_get_contents("list.txt");
$data = explode( "\n", $data );
$cnt = count( $data );
for( $i=0;$i<$cnt;$i++ ){

$array = explode($SPLIT, $data[$i]);
$name = htmlspecialchars($array[0]);
$url = htmlspecialchars($array[1]);
$url = str_replace(PHP_EOL, "", $url);
$data[$i] = $name;
$echomoji = "";

if ($keyword == $data[$i]){
$kekka++;
$echomoji = <<<EOF
<br><a href="{$url}">{$data[$i]}</a>
EOF;
}
elseif ($keyword == ""){
}
else
{
if(strpos($data[$i], $keyword) !== false){
$kekka++;
$echomoji = <<<EOF
<br><a href="{$url}">{$data[$i]}</a>
EOF;
}

if(strpos($keyword, $data[$i]) !== false){
$kekka++;
$echomoji = <<<EOF
<br><a href="{$url}">{$data[$i]}</a>
EOF;
}
}

echo $echomoji;

}
if ($kekka == 0){
echo "<br><br>{$keyword}に関する結果は見つかりませんでした。";
echo "<title>結果は見つかりませんでした。</title>";
}
else
{
echo "<br><br>{$kekka}件の検索結果";
echo "<title>{$kekka}件の検索結果</title>";
}
}
else
{
?>
<div id="form">
<form method="POST" action="">
<input type="text" name="keyword" placeholder="ここに検索ワードを入力">
<input type="submit" value="検索">
</div>
</div>
<?php
}

こんな簡単に作れるとは思いませんでした。
まああくまで初心者が作ったプログラムなので参考程度にお願いします。
例を作ってみました。

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?