使用php从文本文件中只读取前十个单词

时间:2016-09-21 08:55:10

标签: php file-handling

<!-- Modal -->
<div class="modal fade" id="noteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel"></h4>
            </div>
            <div class="modal-body">
                <textarea class="form-control" rows="15" id="fullnote"></textarea>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

我只想存储该行的前十个单词。我怎样才能做到这一点? 目前它正在保存第一行。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

不确定您的数据是否包含逗号或其他符号。 这可能是快速解决方案,它也适用于CJK词。

    <?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); 

    ?>