逐行读取文件&替换第二次出现的子串

时间:2014-05-20 05:40:35

标签: php regex file-io substring

我的txt文件包含

这样的行
some text <POINT> some other text <POINT> more text
varied text <POINT> some more varied text <POINT> different text
one occurrence of <POINT> so no change in this line
and so on...

我需要逐行阅读此文件,并将&lt; POINT&gt; 第二次出现(如果存在)替换为其他内容。

可能起点就是这段代码,但我在成功击中钉子时运气不佳。

$file = fopen("file.txt", "r");
while(!feof($file)){
    $line = fgets($file);
    //here replacement in $line is needed to be done
}
fclose($file);

我是php新手,所以正确执行正则表达式或任何将被appriciated。感谢

2 个答案:

答案 0 :(得分:0)

我认为这会对你有所帮助,我没有检查代码,

$inc1="changed value for 2nd <POINT>"
$inc2="changed value for last <POINT>"
$file = file_get_contents("file.txt") . "<POINT>blabla";
$contents=explode("<POINT>",$file);
$i=0;
$value="";
foreach($contents as $cont)
{
//changing 2nd <point>
if($contents[1] == $contents[$i])
{
$cont=$cont . $inc1;
}
//changing last <point>
elseif(!isset($contents[$i+2]))
{
$cont=$cont . $inc2;
}
elseif(!isset($contents[$i+1]))
{
unset($cont);
}
$value .=$cont . "<POINT>";
$i++;
}

此代码将仅替换

的第二次和最后一次出现

答案 1 :(得分:0)

读取并替换第二次出现的子串

function get_strpos($search, $string, $occurrence) {
  $arr = explode($search, $string);
  switch( $occurrence ) {
    case $occurrence == 0:
      return FALSE;
    case $occurrence > max(array_keys($arr)):
      return FALSE;
    default:
      return strlen(implode($search, array_slice($arr, 0, $occurrence)));
  }
}

function str_second_replace($search, $replace, $string)
{
    $pos = get_strpos($search, $string, 2);

    if($pos !== FALSE)
    {
       $str = substr ( $string , 0, $pos );
       $str .= $replace.substr ( $string , strlen($search)+$pos);
       return $str;
    }

    return $string;
}



$file = fopen("file.txt", "r");
while(!feof($file)){
    $line = fgets($file);
    $search = '<POINT>';
    $replace = '';
    $str=str_second_replace($search,$replace, $line);
    echo $str; // or your business logic
}
fclose($file);