如何阅读文章文件到字符串?

时间:2015-01-08 08:39:30

标签: php function

我希望PHP阅读我的文章文本文件。

示例文本文件:

OMG! Where is my right hand.

I try to find my right hand but I can't see it.

please tell me how to find it.

现在我有了这个功能代码

function getContent($file_path,$path=''){
        $file_path = $file_path;
        if(file_exists('./'.$file_path)){
            $f_read = fopen($path.$file_path,'r');
            $rs = "";
            while (!feof($f_read)) {
                $rs .= fread($f_read, 8192);
            }
            fclose($f_read);
        }
        else{
            echo $rs = "Not Connect File !";
        }
        return($rs);
    }

使用该代码后:

OMG! Where is my right hand. I try to find my right hand but I can't see it. please tell me how to find it.

我想使用PHP函数读取第一行到string1,第一行之后是string2就像这样

$string1 = "OMG! Where is my right hand."

$string2 = "I try to find my right hand but I can't see it.

    please tell me how to find it."

请帮帮我:)。

4 个答案:

答案 0 :(得分:0)

为了将第一行读入$ string1,将其余文件读入$ string2 ...

阅读第一行,如上所述,然后致电file_get_contents以完成剩下的工作。

使用offset参数告诉file_get_contents()在第一行结束后开始读取(传递第一行的字符串长度)。

答案 1 :(得分:0)

您可以使用以下代码将段落拆分为字符串,并从您希望段落拆分的位置指定字符(如句号,逗号等)。

preg_split('/[.?!]/',$mystring);

您可以参考此链接以获取更多信息:Explode a paragraph into sentences in PHP

http://php.net/manual/en/function.explode.php

答案 2 :(得分:0)

您可以使用$string=@file_get_contents($path_name); $string=@explode("\n",$string); //for get each line.

答案 3 :(得分:-1)

尝试使用PHP的explode()函数

function getContent($file_path,$path=''){
            $file_path = $file_path;
            if(file_exists('./'.$file_path)){
                $f_read = fopen($path.$file_path,'r');
                $rs = "";
                while (!feof($f_read)) {
                    $rs .= fread($f_read, 8192);
                    $demo=explode('.', $rs);
                }
                fclose($f_read);
            }
            else{
                echo $rs = "Not Connect File !";
            }
            return($demo);//result wiil be stored in $demo array like $demo[0], $demo[1]
        }