Home > database >  Extracting random sentence from larger text string based on int value
Extracting random sentence from larger text string based on int value

Time:06-30

What I'm attempting to do here is feed into a function an article of words (could be anywhere from 100 to 500 words), once the article is fed in I am trying to randomly grab parts of the article depending on an int so for example if the int is 10 then I just need 10 words returned (but in order so the string makes sense) not the first 10 words of the article, it must be different each time.

Code:

<?php

function get_random_paragraph_from_article($article, $articleWordsCount)
{
    $spun = array();
    $text_array = explode(" ", $article);
    if (count($text_array) > $articleWordsCount) {
        $text = shuffle($text_array);      
        foreach ($text as $value) {
            $spun .= $value . " ";
        }
    }
    return $spun;
}


if (isset($_GET['getRandomArticle'])) {
    
    include($_SERVER['DOCUMENT_ROOT'] . "/includes/inc-db-connection.php"); 
    
    $pdo = new PDO(sprintf('%s:host=%s;dbname=%s', DRIVER, HOST, DATA), USER, PASS);
    
    $command = $pdo->prepare("SELECT * FROM `articles` WHERE `article_keyword` LIKE '%{$_GET['q']}%' ORDER BY RAND() LIMIT 1");
    $command->execute();  
    
    while ($row = $command->fetch()) {      
        echo print_r(get_random_paragraph_from_article($row['article_body'], $_GET['count']));                        
    }       

}

?>

What I do know is I need to split each word into an array which I have done here $text_array = explode(" ", $article); from here is where I get confused as to what the next step should be, I have tried Googling but nothing similar comes up that I can see, any help would be appreciated.

CodePudding user response:

You seem to be getting close, But your shuffle will make the sentences confusing as you no longer have the words in a meaningful order. Rather, you can take a random number rand() and then use it as the starting point of the words you want. As long as count(textArray) >= rand() articleWordCount, you can loop through the array from the starting index of rand() to articleWordCount.

function get_random_paragraph_from_article($article, $articleWordsCount)
{
    $spun = array();
    $max_words = count($text_array) - $articleWordsCount;
    $random_article_starting_point = rand(0,$max_words);
    $text_array = explode(" ", $article);
    if (count($text_array) > $articleWordsCount) {
        $spun = array_splice($text_array, $random_article_starting_point, $articleWordsCount);
    }
    return $spun; //Seems like you initially wanted an array
}

array_splice will get part of an array at the starting point until the offset.

Docs: array_splice: https://www.php.net/manual/en/function.array-splice.php rand: https://www.php.net/manual/en/function.rand.php

  •  Tags:  
  • php
  • Related