duanmianxue2687 2015-07-08 05:05
浏览 42
已采纳

php如何从文本文件中获取特定字符后的整行?

I have text file

name,name1
willhaveishere1
name,name2
willhaveishere2
name,name3
willhaveishere3

i want read it and return like that

$nn = name1
$ss = willhaveishere1

with my code i get only name1

my code is

$file1 = "file.txt";
$file = file($file1);
$count = count($file);
if($count > 0) {
$i = 1;
foreach($file as $row) {
$n = strstr($row, 'name,');
$cc = array("name,");
$dd   = array("");
$nn = str_replace($cc, $dd, $n);
echo $nn;
$i++; } }
  • 写回答

3条回答 默认 最新

  • doudouchan5830 2015-07-08 05:27
    关注

    This is probably what you need

    if($count > 0) {
        foreach($file as $row) {
            $pos = strpos($row, ',');
            if($pos !== false){
                echo substr($row, $pos + 1);
                $nn[] = substr($row, $pos + 1);
            } else {
                echo $row;
                $ss[] = $row;
            }
        }
    }
    

    EDIT

    Yes, just loop through, but make sure both $nn and $ss has same count, which is depending on your file.

    Also Note: mysql_* functions has been deprecated, so please use mysqli or PDO instead

    $count = count($nn);
    for($i=0; $i < $count; $i++){
        $sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]')"; mysql_query($sql); 
    }
    

    EDIT 2

    try this example:

    $file = array(
        0 => 'name,name1',
        1 => 'willhaveishere1',
        2 => 'name,name2',
        3 => 'willhaveishere2',
        4 => 'name,name3',
        5 => 'willhaveishere3'
    );
    $count = count($file);
    if($count > 0) {
        foreach($file as $row) {
            $pos = strpos($row, ',');
            if($pos !== false){
                $nn[] = substr($row, $pos + 1);
            } else {
                $ss[] = $row;
            }
        }
    }
    
    echo '<pre>';
    $count = count($nn);
    for($i=0; $i < $count; $i++){
        $sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]');"; 
        echo $sql.PHP_EOL;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源