我是 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”
最佳答案
删除数字:
$str = preg_replace("/\d/", "", "This 1 is 01 2 a 2 test 4 45 aaa");
echo $str;
输出:
这是一个测试aaa
Link to fiddler
用“hello world”替换整行(仅当它以“example”开头时):
$str = "example This 1 is 01 2 a 2 test 4 45 aaa";
echo preg_replace("/^example.*/", "hello world", $str);
输出:
Hello World
Link to fiddler
将两者结合在一起会给我们:
$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;
}
关于php - 我如何在php中的txt中隐藏字符串中的一些单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12926376/