【问题标题】:How to read article text file to string?如何将文章文本文件读取为字符串?
【发布时间】:2015-01-08 08:39:30
【问题描述】:

我希望 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."

请帮帮我:)

【问题讨论】:

  • 回答者:请阅读问题。 OP 想要将第一行读入 $string1 并将文件的其余部分读入 $string2 - 你似乎没有解决那个 8 并且他为什么会被否决?)

标签: php function


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      为了将第一行读入 $string1 并将文件的其余部分读入 $string2 ...

      像上面一样阅读第一行,然后致电file_get_contents 获取其余内容。

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

      【讨论】:

        【解决方案4】:

        尝试使用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]
                }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-10
          • 2016-07-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多