2

我是 php 新手,并且有以下代码来显示我网站中 .txt 文件中的字符串:

<?php
$file = "file.txt";
$f = fopen($file, "r");
while ( $line = fgets($f, 1000) ) {
    print $line;
}
?>

我想知道如何选择一些要隐藏的单词。就我而言,我想隐藏行中的数字 (01,02,03,04,05,1,2,3,4,5)。我还想将整行替换为另一行,以防它以某个单词开头。例如,如果该行以单词“example”开头,则替换整行并仅显示单词“hello world”

4

3 回答 3

4

要删除数字:

$str = preg_replace("/\d/", "", "This 1 is 01 2 a 2 test 4 45 aaa");
echo $str;

输出:
这是一个测试 aaa

指向 fiddler 的链接


用“hello world”替换整行(仅当它以“example”开头时):

$str =  "example This 1 is 01 2 a 2 test 4 45 aaa";
echo preg_replace("/^example.*/", "hello world", $str);

输出:

你好世界

链接到提琴手


将两者结合在一起将为我们提供:

   $file = "file.txt";
   $f = fopen($file, "r");
   while ( $line = fgets($f, 1000) ) {
      $line = preg_replace("/^example.*/", "hello world", $line);
      $line = preg_replace("/\d/", "", $line);
     print $line;

   }
于 2012-10-17T03:07:18.723 回答
2
<?php
   $hideStartWith = "example";
   $replaceWith = "hello world";
   $hideText = array("01","02","03","04","05","1","2","3","4","5");

   $file = "file.txt";
   $f = fopen($file, "r");
   while ( $line = fgets($f, 1000) ) {
      if(substr($line, 0, strlen($hideStartWith)) === $hideStartWith){
         $line = $replaceWith;  //print "hello world" if the line starts with "example"
     } else {
         foreach($hideText as $h)
             $line = str_replace($h, "", $line); //filtering the numbers
     }

     print $line;

   }
?>

希望这可以帮助。

于 2012-10-17T03:10:55.887 回答
1

对于整行替换​​,请尝试:

if (stripos($my_line, "example")===0){
     $my_line = "example";
}

http://php.net/manual/en/function.str-replace.php

于 2012-10-17T03:02:51.040 回答