-1
<?php
    include 'db_connection.php';

    if (isset($_POST['submit'])) {

    $file = fopen("quiz3.txt","r") or die("Unable to open file!");

    $line = fgets($file);

    $sql = "INSERT INTO quiz3 (FromFile) VALUES ('".$line."')";

    $result = mysqli_query($conn,$sql);

    if (!$result) {

        echo mysqli_error($conn);
    }
    else
    {
        echo "Your File Has Been Read & Stored In Database Successfully<br>Line Stored = ";
        echo $line;
    }

    fclose($file);
    }
?>

I want to store only first ten words from the line. How Can i do that? currently it is saving the first line.

Sadda Hussain
  • 343
  • 5
  • 19

2 Answers2

2
function get_words($sentence, $count = 10) {
  preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
  return $matches[0];
}

$file = fopen("quiz3.txt","r") or die("Unable to open file!");

$line = fgets($file);

$convertedLine = get_words($line );

$sql = "INSERT INTO quiz3 (FromFile) VALUES ('".$convertedLine ."')";

$result = mysqli_query($conn,$sql);
virepo
  • 320
  • 5
  • 22
0

Not sure if your data contains comma, or other symbols. This might be quick solution, and it also works with CJK words.

    <?php
    function cut_words($source, $number_take){
        $result = "";
        $wc = 0;
        $source = str_replace("  ", " ", $source); // Simple sanity
        $string = explode(" ", $source);
        while ($wc < $number_take){
            if(isset($string[$wc])){ // Prevent index out of bound.
                $result .= $string[$wc];
                if($wc < $number_take) {
                    $result .= " ";
                }
            $wc++;
            } else {
                break;
            }
        }
        $result = trim($result);
        return $result;
    }

    $line = cut_words($line, 10); 

    ?>
HZS
  • 167
  • 7