2013년 12월 10일 화요일

PHP 단어 수 세는 소스

1. index.php
  • vim /var/www/dwhan/index.php
 <?php
include "wordCheck.php";

if (isset($_POST['content']))
{    $wordCheck = new WordCheck;
    $content = stripslashes($_POST['content']);
    $exploded = $wordCheck->MultiExplode($content);
    $wordList = $wordCheck->GetWordList($exploded);}
?>
 
<?php echo "Input " ?>
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
    <textarea rows="25" cols="60" name="content"></textarea>
    <input type="submit" value="Save"></form>
 
<textarea rows="35" cols="60" name="result">
<?php foreach($wordList as $key => $value)
        {
            foreach($value as $key => $value)
            {
                echo "Word : " . $key . "  " . "Count : " . $value . "\n";
            }        }
?></textarea>
 
2. wordCheck.php
  • vim /var/www/dwhan/wordCheck.php
<?php
class WordCheck
{
    var $delimiters = array('\"', '?', '<', '>', '(', ')',
                         '!', '-', '/', ',', '.', '|', '=', ':', ' ', "\r\n", "\t");

    function MultiExplode($string)
    {
        $ready = str_replace($this->delimiters, $this->delimiters[0], $string);
        $launch = explode($this->delimiters[0], $ready);
        return  $launch;   
    }

    function GetWordList($exploded)
    {
        $word = array();       
        $unique = (array_unique($exploded));

        foreach($unique as $token)
        {
            if (strcmp("\r\n", $token) == -1 || strcmp(" ", $token) == -1)
            {
                $count = count(array_keys($exploded, $token));
                $temp = array($token => $count);  // 뽑아낸 단어와 카운트를 인덱스를 토큰으로 지정하여 배열에 저장
                array_push($word, $temp); // 생성한 배열을 추가
            }
        }
        return $word;
    }
}
?>

댓글 없음:

댓글 쓰기