Example #1
0
function recursiveMenuSideBar($id_cha)
{
    $categories = DB::table('categories')->where('parent_id', '=', $id_cha)->get();
    $word = array();
    foreach ($categories as $category) {
        $numOfWord = str_word_count($category->name);
        $word = explode(' ', $category->name);
        $link = '';
        if ($numOfWord > 1) {
            for ($i = 0; $i < $numOfWord; $i++) {
                $link .= $word[$i];
            }
        } else {
            $link = $category->name;
        }
        echo "<option><a href='http://localhost/HungNH/public/{$link}'>";
        $name = '';
        for ($i = 0; $i < $category->level; $i++) {
            $name .= '&nbsp&nbsp';
        }
        $name .= '' . $category->name;
        echo $name;
        echo "</option>";
        $haveChild = haveChild($category->id);
        if ($haveChild > 0) {
            recursiveMenuSideBar($category->id);
        }
    }
}
Example #2
0
function umwords_build($p, $o)
{
    $ratio = 50;
    $min = $p * $ratio;
    $limit = $min . ', ' . ($min + $ratio);
    $r = sql_inner('pub_art.id,msg', 'qda', 'qdm', 'id', 'kv', 'where nod="ummo" limit ' . $limit);
    if ($r) {
        foreach ($r as $k => $v) {
            $v = str_replace("'", ' ', $v);
            //$v=str_replace('-',' ',$v);
            $rb = str_word_count($v, 2);
            if ($rb) {
                foreach ($rb as $ka => $va) {
                    if ($va == strtoupper($va) && !umwords_dicos($va) && strlen($va) > 1) {
                        $rd[] = array($k, $va, $ka, soundex($va));
                        //idart,voc,pos,sound
                        $rc[$va] = array($k, $va, $ka, soundex($va));
                    }
                }
            }
        }
    }
    //if(auth(6))umwords_sav($rc);
    return $rd;
    $ret = count($rc);
    $ret .= make_table($rc);
    return $ret;
}
function contentSearch($url)
{
    $dom = new DOMDocument();
    @$dom->loadHTMLFile($url);
    //$dom->loadHTML( '<?xml encoding="UTF-8">' . $content );
    $output = array();
    $csv_file = $_POST['csv_file'];
    $xpath = new DOMXPath($dom);
    $textNodes = $xpath->query('//text()');
    foreach ($textNodes as $textNode) {
        $parent = $textNode;
        while ($parent) {
            if (!empty($parent->tagName) && in_array(strtolower($parent->tagName), array('pre', 'code', 'a')) && str_word_count($parent->nodeValue) > 6) {
                continue 2;
            }
            if (str_word_count($parent->nodeValue) < 6 && !empty($parent->tagName)) {
                $job_title_file = fopen("{$csv_file}" . ".csv", 'r');
                while ($row = fgetcsv($job_title_file)) {
                    $nv = strip_tags($parent->nodeValue);
                    if (preg_match("/\\b" . $row[0] . "\\b/i", $nv)) {
                        //job title found
                        //echo $parent->tagName . '===' . $parent->nodeValue . '===' .  $row[0] . '<br />';
                        $output[] = array($nv, '');
                        fclose($job_title_file);
                        break;
                    }
                }
            }
            $parent = $parent->parentNode;
        }
        //end while parent
    }
    //end  for
    return $output;
}
/**
 * findWord
 *
 * Compute the word that contains the highest number of repeated charaters
 * from the supplied text file
 *
 * @param  string $filePath The search text
 * @return string       The word with the highest number of charaters
 */
function findWord($filePath)
{
    if (!is_readable($filePath)) {
        throw new \RuntimeException(sprintf('The file path \'%s\' is not readable.', $filePath));
    }
    $text = file_get_contents($filePath);
    if (false === $text) {
        throw new \RuntimeException(sprintf('An error occured while trying to read the contents of \'%s\'', $filePath));
    }
    if (empty($text)) {
        throw new \DomainException(sprintf('The text file \'%s\' contains no text!', $filePath));
    }
    $winningWord = null;
    $charCount = 0;
    foreach (str_word_count(strtolower($text), 1) as $word) {
        $counts = count_chars($word, 1);
        if (!empty($counts)) {
            rsort($counts);
            $count = current($counts);
            if ($charCount == 0 || $count > $charCount) {
                $winningWord = $word;
                $charCount = $count;
            }
        }
    }
    return $winningWord;
}
Example #5
0
 /**
  * Checks if the given value matches the specified maximum words.
  *
  * @param mixed $value The value that should be validated
  * @return void
  */
 public function isValid($value)
 {
     $maximumWords = $this->options['maximumWords'];
     if (str_word_count($value) > $maximumWords) {
         $this->addError('Verringern Sie die Anzahl der Worte - es sind maximal ' . $maximumWords . ' erlaubt!', 1383400016);
     }
 }
Example #6
0
 /**
  * Return a truncated string by the number of words
  */
 public static function truncateWords($str, $words)
 {
     if (str_word_count($str) > $words) {
         $str = trim(preg_replace('/((\\w+\\W*){' . $words . '}(\\w+))(.*)/', '${1}', $str)) . '&hellip;';
     }
     return $str;
 }
Example #7
0
 /**
  * Get a single keyword from a string or array of sanitized words.
  *
  * @access private
  *
  * @param string|array $words Array or string of sanitized words
  * 
  * @return string A single keyword
  */
 private function get_keyword($words)
 {
     // Make a string from array if array is provided
     if (is_array($words)) {
         $words = implode(' ', $words);
     }
     // Get an array of all words contained in the string
     $words = str_word_count($words, 1);
     // Get the count of all words
     $total_words = count($words);
     // Count all the values in the array and sort by values
     $word_count = array_count_values($words);
     arsort($word_count);
     // Holder for parsed words
     $new_words = array();
     // Loop through the words and score each into a percentage of word density
     foreach ($word_count as $key => $value) {
         $new_words[$key] = number_format($value / $total_words * 100);
     }
     // Pop the first word off the array
     reset($new_words);
     $first_key = key($new_words);
     // And return it
     return $first_key;
 }
function bind_listdomains()
{
    $array_listado = array();
    $lines = file(_CFG_BIND_CFG_FILE);
    $i = 0;
    foreach ($lines as $line_num => $line) {
        if (substr($line, 0, 2) != "//") {
            $cadena = str_word_count($line, 1);
            if ($cadena[0] == "zone") {
                $linea_zona = trim($line);
                $pos_ini = strpos($linea_zona, '"');
                $pos_fin = strpos($linea_zona, '"', $pos_ini + 1);
                $zona = substr($linea_zona, $pos_ini + 1, $pos_fin - strlen($linea_zona));
                if (!word_exist($zona, _CFG_BIND_IGNORE_FILE)) {
                    $array_listado[$i] = trim($zona);
                    $i++;
                }
            }
            if ($cadena[0] == "file") {
                $linea_fichero = trim($line);
                $pos = strpos($linea_fichero, '"');
                $fichero = trim(substr($linea_fichero, $pos + 1, -2));
            }
        }
    }
    sort($array_listado);
    return $array_listado;
}
Example #9
0
 /**
  * @param string $name
  *
  * @throws ElementNotFoundException
  *
  * @return NodeElement
  */
 public function findField($name)
 {
     $currency = null;
     if (1 === preg_match('/in (.{1,3})$/', $name)) {
         // Price in EUR
         list($name, $currency) = explode(' in ', $name);
         return $this->findPriceField($name, $currency);
     } elseif (1 < str_word_count($name)) {
         // mobile Description
         $words = explode(' ', $name);
         $scope = array_shift($words);
         $name = implode(' ', $words);
         // Check that it is really a scoped field, not a field with a two word label
         if (strtolower($scope) === $scope) {
             return $this->findScopedField($name, $scope);
         }
     }
     $label = $this->find('css', sprintf('label:contains("%s")', $name));
     if (!$label) {
         throw new ElementNotFoundException($this->getSession(), 'form label ', 'value', $name);
     }
     $field = $label->getParent()->find('css', 'input,textarea');
     if (!$field) {
         throw new ElementNotFoundException($this->getSession(), 'form field ', 'id|name|label|value', $name);
     }
     return $field;
 }
Example #10
0
 /**
  * Add method
  *
  * @return void Redirects on successful add, renders view otherwise.
  */
 public function add()
 {
     $accumulatedPoints = array();
     $point = $this->Points->newEntity();
     if ($this->request->is('post')) {
         $point = $this->Points->patchEntity($point, $this->request->data);
         if ($this->Points->save($point)) {
             $this->Flash->success(__('The point has been saved.'));
             return $this->redirect(['action' => 'index']);
         } else {
             $this->Flash->error(__('The point could not be saved. Please, try again.'));
         }
     }
     $username = $this->Points->Users->find('list', ['keyField' => 'id', 'valueField' => 'name'], ['limit' => 200])->toArray();
     $users = $this->Points->Users->find('all', ['contain' => ['Diarys', 'Historys', 'Points', 'Words', 'CompletedWords']]);
     //make array of most recent accumulated points
     foreach ($users as $user) {
         $sum = 0;
         foreach ($user->diarys as $diary) {
             $sum = $sum + str_word_count($diary['body']) % $this->maxWord * $this->rateJournalWord;
         }
         $numWords = 0;
         foreach ($user->words as $word) {
             if ($word->meaning != null) {
                 $numWords++;
             }
         }
         $accumulatedPoints[$user->id] = $numWords * $this->rateAddWord + count($user->completed_words) * $this->rateFinishWord + count($user->diarys) * $this->rateJournal + count($user->historys) * $this->rateHistory + $sum;
     }
     //make array of most recent remained points
     $remainedPoints = $this->Points->find('list', ['keyField' => 'user_id', 'valueField' => 'remained_points'], ['limit' => 200])->order(['id' => 'ASC'])->toArray();
     $this->set(compact('point', 'accumulatedPoints', 'remainedPoints', 'username'));
 }
Example #11
0
 public function test($target)
 {
     $DOM = $target;
     $page = $DOM->saveHTML();
     $body_elements = $DOM->getElementsByTagName('body');
     $tags = $body_elements->item(0)->childNodes;
     foreach ($tags as $tag) {
         if ($tag->nodeName == "script" || $tag->nodeName == "noscript" || $tag->nodeName == "style") {
             continue;
         }
         if ($tag->nodeName == "p") {
             $this->p_content .= ' ' . $tag->textContent;
         }
         $this->text_content .= $tag->textContent;
     }
     $all_text = $this->text_content;
     $ratio = number_format(strlen($all_text) * 100 / strlen($page), 2);
     $num_words = str_word_count($this->p_content);
     if ($ratio >= 25) {
         $this->result .= '<p><span class="result ok">OK</span>Text / HTML ratio in your website is above 25%.</p><pre>' . $ratio . '% ratio</pre><code>' . $this->text_content . '</code>' . "\n";
         $this->score += 1;
     } else {
         $this->result .= '<p><span class="result warn">WARN</span>Text / HTML ratio in your website is below 25%.</p><pre>' . $ratio . '% ratio</pre><code>' . $this->text_content . '</code>' . "\n";
     }
     if ($num_words >= 300) {
         $this->result .= '<p><span class="result ok">OK</span>Number of words in your text is above 300 words.</p><pre>' . $num_words . ' words</pre><code>' . $this->p_content . '</code>' . "\n";
         $this->score += 1;
     } else {
         $this->result .= '<p><span class="result warn">WARN</span>Number of words in your text is below 300 words.</p><pre>' . $num_words . ' words</pre><code>' . $this->p_content . '</code>' . "\n";
     }
     return array("name" => "textratio", "score" => $this->score, "total_score" => self::TOTAL_SCORE, "result" => $this->result);
 }
Example #12
0
/**
 * Reduce the length of custom excerpt (if specified manually) for widgets.
 *
 * @param string $excerpt Current excerpt
 *
 * @since 1.0.0
 *
 * @return string
 */
function appica_widget_trim_excerpt($excerpt)
{
    if (false === strpos($excerpt, '...') && str_word_count($excerpt) > 9) {
        $excerpt = wp_trim_words($excerpt, 9, ' ...');
    }
    return $excerpt;
}
Example #13
0
function obtainData($objDb, $id)
{
    $aRes = $objDb->GetDetails($id);
    $sText = $objDb->GetRawText($id);
    if ($aRes === FALSE || $sText === FALSE) {
        // No such record!
        return FALSE;
    }
    // Clean up list of words
    $aWords = array_filter(array_unique(str_word_count($sText, 1)), "filter_words");
    // Split words into likely and unlikely (based on spelling)
    $aLikely = array();
    $aUnlikely = array();
    $hSpell = pspell_new("en");
    if ($hSpell !== FALSE) {
        foreach ($aWords as $sWord) {
            // Make a spellcheck on it
            if (pspell_check($hSpell, $sWord)) {
                array_push($aLikely, $sWord);
            } else {
                array_push($aUnlikely, $sWord);
            }
        }
    } else {
        $aLikely = $aWords;
    }
    return array("likely" => $aLikely, "unlikely" => $aUnlikely);
}
Example #14
0
 public function test($target)
 {
     $title = self::extractTitle($target);
     $metatitle = self::extractMetaTitle($target);
     if (strlen($metatitle) >= 1) {
         $this->result .= '<p><span class="result ok">OK</span>The meta title is present: <pre>' . $metatitle . '</pre></p>' . "\n";
         $this->score += 1;
         $metatitle_length = str_word_count($metatitle);
         if ($metatitle_length == 9) {
             $this->result .= '<p><span class="result ok">OK</span>Meta title length is good: <pre>9 words</pre></p>' . "\n";
             $this->score += 1;
         } else {
             $this->result .= '<p><span class="result warn">WARN</span>Meta title length should be 9 words, detected: <pre>' . $metatitle_length . ' words</pre></p>' . "\n";
         }
         $metatitle_length = strlen($metatitle);
         if ($metatitle_length >= 60 && $metatitle_length <= 70) {
             $this->result .= '<p><span class="result ok">OK</span>Meta title length is good: <pre>65 characters</pre></p>' . "\n";
             $this->score += 1;
         } else {
             $this->result .= '<p><span class="result warn">WARN</span>Meta title length should between 60 and 70 characters aprox. (included spaces), detected: <pre>' . $metatitle_length . ' characters</pre></p>' . "\n";
         }
         // title == metatitle
         if (strcmp($title, $metatitle) == 0) {
             $this->result .= '<p><span class="result ok">OK</span>Meta title is equal to page title</p>' . "\n";
             $this->score += 1;
         } else {
             $this->result .= '<p><span class="result error">Error</span>Meta title is different to page title: <pre>' . $title . "\n" . $metatitle . '</pre></p>' . "\n";
         }
     } else {
         $this->result .= '<p><span class="result error">ERROR</span>No meta title detected!</p>' . "\n";
         $this->result .= '<p><span class="result error">ERROR</span>Meta title length should be 9 words and 60 - 70 characters, none is detected.</p>' . "\n";
     }
     return array("name" => "metatitle", "score" => $this->score, "total_score" => self::TOTAL_SCORE, "result" => $this->result);
 }
 public function testTruncatesLongTextToGivenNumberOfWords()
 {
     $nwords = str_word_count(strip_tags(Truncator::truncate($this->long_text, 10, '')));
     $this->assertEquals(10, $nwords);
     $nwords = str_word_count(strip_tags(Truncator::truncate($this->long_text, 11, '')));
     $this->assertEquals(11, $nwords);
 }
Example #16
0
 function build()
 {
     $this->db = new db();
     $this->db->connect('localhost', 'bot', 'dyton', 'bot');
     $this->aliasbuild();
     $this->zerocounts();
     $res = $this->db->query("SELECT * FROM `system`");
     while ($row = mysql_fetch_array($res)) {
         $this->system[$row['field']] = $row['value'];
     }
     $res = $this->db->query("SELECT * FROM `log`");
     while ($row = mysql_fetch_array($res)) {
         $nick = $this->getnick($row['nick']);
         if ($nick != "NORECORD") {
             $hour = date("G", $row['time']);
             $this->gs['total'] += 1;
             $this->gs[$hour] += 1;
             $this->counts[$nick]['lines'] += 1;
             $words = str_word_count($row['s']);
             $this->counts[$nick]['words'] += $words;
             $chars = strlen($row['s']);
             $this->counts[$nick]['chars'] += $chars;
             foreach ($this->regex as $key => $string) {
                 if (preg_match($string, $row['s']) == 1) {
                     $this->counts[$nick][$key] += 1;
                 }
             }
         }
     }
 }
Example #17
0
 public function test($target)
 {
     $title = self::extractTitle($target);
     if ($title) {
         $this->result .= '<p><span class="result ok">OK</span>The title is present: <pre>' . $title . '</pre></p>' . "\n";
         $this->score += 1;
         $title_length = str_word_count($title);
         if ($title_length == 9) {
             $this->result .= '<p><span class="result ok">OK</span>Title length is good: <pre>' . $title_length . ' words</pre></p>' . "\n";
             $this->score += 1;
         } else {
             $this->result .= '<p><span class="result warn">WARN</span>Title length should be 9 words, detected: <pre>' . $title_length . ' words</pre></p>' . "\n";
         }
         $title_length = strlen($title);
         if ($title_length >= 60 && $title_length <= 70) {
             $this->result .= '<p><span class="result ok">OK</span>Title length is good: <pre>' . $title_length . ' characters</pre></p>' . "\n";
             $this->score += 1;
         } else {
             $this->result .= '<p><span class="result warn">WARN</span>Title length should between 60 and 70 characters aprox. (included spaces), detected: <pre>' . $title_length . ' characters</pre></p>' . "\n";
         }
     } else {
         $this->result .= '<p><span class="result error">ERROR</span>No title detected!</p>' . "\n";
         $this->result .= '<p><span class="result error">ERROR</span>Title length should be 9 words and 60 - 70 characters (spaces included), none is detected.</p>' . "\n";
     }
     return array("name" => "title", "score" => $this->score, "total_score" => self::TOTAL_SCORE, "result" => $this->result);
 }
Example #18
0
 public function ajaxCountWords()
 {
     $param = $this->input->post('param');
     if (!empty($param['amount'])) {
         echo str_word_count($param['amount']);
     }
 }
 /**
  * Returns the current payment method
  * @return string
  */
 public function getPaymentMethodProperty()
 {
     $element = Helper::findElements($this, ['currentMethod']);
     $currentMethod = $element['currentMethod']->getText();
     $currentMethod = str_word_count($currentMethod, 1);
     return $currentMethod[0];
 }
Example #20
0
 protected function pruneUserComments(Issue $issue, DoBrowser $browser, $comment_words, InputInterface $input, OutputInterface $output)
 {
     $deleted_comments = 0;
     /** @var \DOMElement $comment */
     foreach ($issue->getCrawler()->filter('section.comments div.comment') as $comment) {
         $words = 0;
         $crawler = new Crawler($comment);
         if ($crawler->filter('.nodechanges-file-changes')->count() > 0) {
             // Has a file attached ignore.
             continue;
         }
         $comment_body = $crawler->filter('.field-name-comment-body div.field-item');
         if ($comment_body->count()) {
             $text = $comment_body->text();
             $words = str_word_count(trim($text));
         }
         // Zero word comments are often issue summary updates extra - ignore them
         // for now.
         if ($words <= $comment_words) {
             $changes = $crawler->filter('.field-name-field-issue-changes div.field-item');
             if ($changes->count()) {
                 $output->writeln("Comment issue changes: " . trim($changes->text()));
             }
             $output->writeln("Comment text: " . trim($text));
             if ($this->askConfirmation($input, $output, 'Delete this comment (yes/NO)? ')) {
                 $delete_link = $crawler->filter('li.comment-delete a, div.system-message.queued-retesting li.comment-delete a')->extract(array('href'));
                 $delete_link = $delete_link[0];
                 $this->deleteComment($delete_link, $browser, $output);
                 $deleted_comments++;
             }
             $output->writeln('');
         }
     }
     $output->writeln("Deleted {$deleted_comments} user comments.");
 }
Example #21
0
function load_post_data()
{
    $args = array('p' => $_POST['post_id']);
    $post_query = new WP_Query($args);
    while ($post_query->have_posts()) {
        $post_query->the_post();
        $postSlug = basename(get_the_permalink());
        $postTitle = get_the_title();
        $postTitleEncoded = urlencode(get_the_title());
        $postDate = get_the_date('l, F j, Y');
        $wordCount = str_word_count(strip_tags(get_the_content()));
        $postLength = round($wordCount / 250);
        $postContent = get_the_content();
        if (in_category("design")) {
            $postLinkTemp = "http://joshbeveridge.com/#designer-post-" . $postSlug;
        }
        if (in_category("gaming")) {
            $postLinkTemp = "http://joshbeveridge.com/#gamer-post-" . $postSlug;
        }
        $postLink = urlencode($postLinkTemp);
        $dataArray = array("post_slug" => $postSlug, "post_link" => $postLink, "post_title" => $postTitle, "post_title_encoded" => $postTitleEncoded, "post_date" => $postDate, "post_length" => $postLength, "post_content" => $postContent);
        echo json_encode($dataArray);
    }
    wp_reset_postdata();
    exit;
}
 public static function filetr(array $result, $limit_chars = self::LIMIT_CHARRS_IN_PHRASE, $limit_words = self::LIMIT_WORDS_IN_PHRASE, $limit_count_words = self::LIMIT_COUNT_PHRASE_IN_QUERY)
 {
     //remove double spaces and do trim
     $result = array_map(function ($data) {
         return trim(preg_replace('/\\s\\s+/', ' ', $data));
     }, $result);
     //remove empty items
     //remove items more LIMIT_CHARRS_IN_PHRASE
     //remove items more LIMIT_WORDS_IN_PHRASE
     $closure = function ($input) use($limit_chars, $limit_words) {
         if (empty($input)) {
             return false;
         }
         if (strlen($input) >= $limit_chars) {
             return false;
         }
         if (str_word_count($input, 0) > $limit_words) {
             return false;
         }
         return true;
     };
     $result = array_filter($result, $closure);
     //sort by strlen items
     usort($result, function ($a, $b) {
         return strlen($a) - strlen($b);
     });
     //array slice result array
     if (count($result) > $limit_count_words) {
         $result = array_slice($result, 0, $limit_count_words);
     }
     return $result;
 }
 function ngrams($data, $max_ngs = DEPTH, $max_n = N)
 {
     $data = preg_replace("/[^a-zA-Z\\s]/", "", $data);
     $words = str_word_count(strtolower($data), 1);
     $ngrams = array();
     // split words into ngramgs
     foreach ($words as $word) {
         $word = $word;
         $length = strlen($word);
         for ($index = 0; $index < $length; $index++) {
             for ($n = 1; $n <= $max_n; $n++) {
                 $ngram = substr($word, $index, $n);
                 if (strlen($ngram) < $n) {
                     continue;
                 }
                 $ngrams[] = $ngram;
             }
         }
     }
     // determine ngram frequency counts
     $frequencies = array_count_values($ngrams);
     arsort($frequencies);
     // throw away all but the top 750 most frequently occuring ngrams
     $frequencies = array_slice($frequencies, 0, $max_ngs);
     return $frequencies;
 }
 public static function GetItemsForCategoryForAPI($category, $page, $itemsPerPage, $user)
 {
     $properties = new ReadeyProperties();
     $logFile = $properties->getLogFile();
     $logLevel = $properties->getLogLevel();
     $logger = new Logger($logLevel, $logFile);
     $limit = intval($itemsPerPage);
     $index = $page > 0 ? ($page - 1) * $itemsPerPage : 0;
     $itemArray = array();
     $startTime = microtime(true);
     $sql = "\n\t\t\tSELECT\n\t\t\t\tDISTINCT\n\t\t\t\tSQL_CALC_FOUND_ROWS\n\t\t\t\tri.uuid,\n\t\t\t\trf.title AS feedTitle,\n\t\t\t\tri.title,\n\t\t\t\tri.date,\n\t\t\t\trl.rssItemUuid AS alreadyRead,\n\t\t\t\tri.permalink,\n\t\t\t\tri.content\n\t\t\tFROM\n\t\t\t\trssItems ri\n\t\t\t\tJOIN rssFeeds rf ON rf.uuid = ri.feed\n\t\t\t\tJOIN rssCategories rc ON rc.uuid = rf.category\n\t\t\t\tLEFT JOIN readLogs rl ON rl.rssItemUuid = ri.uuid AND rl.user = '******'\n\t\t\t\tJOIN category_feed cf ON cf.feed = ri.feed\n\t\t\tWHERE\n\t\t\t\tcf.category = '{$category}'\n\t\t\tORDER BY\n\t\t\t\tdate DESC\n\t\t\tLIMIT " . $index . "," . $limit . "\n\t\t";
     $result = mysql_query($sql);
     $queryTime = microtime(true) - $startTime;
     $resultCount = mysql_query("SELECT FOUND_ROWS()");
     $resultCountRows = mysql_fetch_array($resultCount);
     $itemArray[] = $resultCountRows[0];
     $itemArray[] = $queryTime;
     $logger->info('Query Exec Time: ' . $queryTime);
     while ($row = mysql_fetch_assoc($result)) {
         $row['date'] = date('D, n/j, g:i a', $row['date']);
         $row['wordCount'] = str_word_count($row['content']);
         $row['alreadyRead'] = $row['alreadyRead'] === NULL ? false : true;
         $itemArray[] = $row;
     }
     return $itemArray;
 }
    public function testLimitDescription()
    {
        $text = <<<EOT
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, nam rhoncus consectetur arcu non sodales - interdum et malesuada fames ac ante ipsum primis in faucibus! Cras suscipit sed risus a eleifend, donec fermentum aliquet bibendum, quisque ac finibus tellus. Sed massa urna, tristique sed sodales vitae, tempus ut nisl. Nulla interdum condimentum metus, at interdum tortor aliquam et. Morbi quis varius quam, sit amet placerat mauris. Quisque sit amet sem dictum, tincidunt sem at, semper turpis. Mauris ut nunc ante. In vehicula viverra nisl in posuere. Pellentesque quis orci vel eros euismod accumsan vitae nec risus.
</p>
<p>
Donec ornare sapien est. Phasellus dignissim ullamcorper erat, quis dictum enim. Nam in dui vel nisl rutrum pharetra at sit amet lorem. Praesent in odio ante. Sed risus libero, maximus eu molestie eget, bibendum quis nisl. Mauris efficitur turpis ut orci aliquam gravida. Duis at scelerisque urna.
</p>
<p>
Integer eget ultrices eros. In libero ligula, placerat ac ligula vitae, tincidunt euismod velit. Quisque suscipit vulputate libero nec aliquam. Fusce ut ligula tincidunt, placerat ante sed, iaculis odio. Proin at sodales eros. Nulla ultrices pulvinar mollis. Pellentesque feugiat varius tortor et egestas. Vivamus faucibus rhoncus rhoncus. Aliquam erat volutpat. Praesent vestibulum mauris sed vestibulum semper. Suspendisse ornare felis eu tristique lobortis. Duis bibendum sodales ex, consectetur porta neque malesuada et. Aliquam eros sapien, finibus vel mattis non, convallis a purus.
</p>
<p>
Nulla nibh tortor, viverra quis pretium ut, semper in lacus. Ut fermentum quam nec tortor finibus finibus. In dapibus sollicitudin lacus, quis mattis nisl semper id. Aenean vel sodales nisl. Sed tincidunt ante a felis consequat, ac faucibus lorem pretium. Maecenas at erat viverra, varius dui eget, egestas nisi. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam sollicitudin nisi ut nulla mattis, at accumsan velit interdum. Suspendisse ac nisl sapien. Proin felis odio, vehicula dictum eros nec, dignissim ornare dui. Vestibulum accumsan, tortor nec mollis eleifend, ligula neque commodo tellus, a placerat sapien orci ac urna. Aliquam vitae eros et nisl euismod rhoncus nec vitae mi. Sed tortor justo, placerat ac augue vitae, porta hendrerit neque.
</p>
<p>
Nam nec turpis sed ipsum venenatis convallis id eget nunc. Nam nec mauris ac diam consequat consectetur. Morbi in dolor est. Nulla eget tortor ac tortor dignissim suscipit ac nec augue. Integer quis auctor elit, sed malesuada mi. Nunc a augue libero. Vestibulum venenatis neque enim, ut malesuada orci faucibus at. Vivamus quis viverra magna, a maximus arcu. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam pellentesque felis et dolor egestas feugiat. Cras pretium cursus porta. Aenean ut quam laoreet, placerat mi auctor, varius risus. Nunc vel urna et odio cursus malesuada.</p>

EOT;
        // Best practices:
        // - max ~155 chars
        // - 25-30 words
        // - 2 sentences
        $parser = new Metaculous\Parser();
        $description = $parser->description($text);
        $this->assertTrue(strlen($description) <= 155);
        $this->assertTrue(str_word_count($description) <= 30);
        $sentences = preg_split("@[\\.!\\?]+@m", preg_replace('@\\.+$@', '', $description));
        $this->assertTrue(count($sentences) <= 2);
    }
 /** Function make request to Google translate, download file and returns audio file path 
  * @param     String     $text        - Text to speak 
  * @param     String     $lang         - Language of text (ISO 639-1) 
  * @return     String     - mp3 file path 
  * @link https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes 
  */
 function speak($text, $lang = NULL)
 {
     $this->text = $text;
     // Can not handle more than 100 characters
     $this->text = substr($this->text, 0, $this->maxStrLen);
     // Text lenght
     $this->textLen = strlen($this->text);
     // Words count
     $this->wordCount = str_word_count($this->text);
     // Encode string
     $this->text = urlencode($this->text);
     // Create dir if not exists
     if (!is_dir($this->audioDir)) {
         mkdir($this->audioDir, 777) or die('Could not create audio dir: ' . $this->audioDir);
     }
     // Generate unique mp3 file name
     $this->mp3File = sprintf($this->mp3File, $this->audioDir . md5($this->text));
     // Download new file or use existing
     if (!file_exists($this->mp3File)) {
         $this->download("http://translate.google.com/translate_tts?ie=UTF-8&q={$this->text}&tl={$lang}", $this->mp3File);
         /*$this->download("http://translate.google.com/translate_tts?q={$this->text}&tl={$lang}", $this->mp3File);  */
     }
     // Returns mp3 file path
     return $this->mp3File;
 }
Example #27
0
 function calculate_word_popularity($string, $min_word_char = 2, $exclude_words = array())
 {
     $string = strip_tags($string);
     $initial_words_array = str_word_count($string, 1);
     $total_words = sizeof($initial_words_array);
     $new_string = $string;
     foreach ($exclude_words as $filter_word) {
         $new_string = preg_replace("/\\b" . $filter_word . "\\b/i", "", $new_string);
         // strip excluded words
     }
     $words_array = str_word_count($new_string, 1);
     $words_array = array_filter($words_array, create_function('$var', 'return (strlen($var) >= ' . $min_word_char . ');'));
     $popularity = array();
     $unique_words_array = array_unique($words_array);
     foreach ($unique_words_array as $key => $word) {
         preg_match_all('/\\b' . $word . '\\b/i', $string, $out);
         $count = count($out[0]);
         $percent = number_format($count * 100 / $total_words, 2);
         $popularity[$key]['word'] = $word;
         $popularity[$key]['count'] = $count;
         $popularity[$key]['percent'] = $percent . '%';
     }
     function cmp($a, $b)
     {
         return $a['count'] > $b['count'] ? +1 : -1;
     }
     usort($popularity, "cmp");
     return $popularity;
 }
 /**
  * Register the application services.
  */
 public function register()
 {
     /*
      * Validates a minimum words required
      * @example min_words:1
      */
     $this->app['validator']->extend('min_words', function ($attribute, $value, $parameters) {
         return str_word_count($value) >= array_get($parameters, 0, 1);
     });
     /*
      * Validate a maximun words required
      * @example max_words:10
      */
     $this->app['validator']->extend('max_words', function ($attribute, $value, $parameters) {
         return str_word_count($value) <= array_get($parameters, 0, 1);
     });
     /*
      * Replace the :words in messages for min_words rules.
      */
     $this->app['validator']->replacer('min_words', function ($message, $attribute, $rule, $parameters) {
         return str_replace(':words', $parameters[0], $message);
     });
     /*
      * Replace the :words in messages for max_words rules.
      */
     $this->app['validator']->replacer('max_words', function ($message, $attribute, $rule, $parameters) {
         return str_replace(':words', $parameters[0], $message);
     });
 }
function recursiveMenu($id_cha)
{
    $categories = DB::table('categories')->where('parent_id', '=', $id_cha)->get();
    ?>
    	<ul class="dropdown2">
    	<?php 
    $word = array();
    foreach ($categories as $category) {
        $numOfWord = str_word_count($category->name);
        $word = explode(' ', $category->name);
        $link = '';
        if ($numOfWord > 1) {
            for ($i = 0; $i < $numOfWord; $i++) {
                $link .= $word[$i];
            }
        } else {
            $link = $category->name;
        }
        echo "<li value='{$category->id}'><a href='http://localhost/HungNH/public/{$link}'>";
        $name = '';
        $name .= '' . $category->name;
        echo $name;
        echo "</a></li>";
        $haveChild = haveChild($category->id);
        if ($haveChild > 0) {
            recursiveMenu($category->id);
        }
    }
    ?>
		</ul>
		<?php 
}
Example #30
-1
 /**
  * Updates post_meta with number of words
  * @author Eric Wennerberg
  * @since 0.0.7
  * @version 0.2.0
  * @param str $post_id
  * @return int $words;
  */
 function helpers_calculate_read_time($post_id)
 {
     $content = apply_filters('the_content', get_post_field('post_content', $post_id, 'raw'));
     $words = str_word_count($content);
     update_post_meta($post_id, 'flavour_num_words', $words);
     return $words;
 }