如何在php中从txt隐藏字符串中的一些单词
我是php新手,使用以下代码显示web中.txt文件中的字符串:如何在php中从txt隐藏字符串中的一些单词,php,text,show-hide,words,Php,Text,Show Hide,Words,我是php新手,使用以下代码显示web中.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
<?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”,请尝试:
if (stripos($my_line, "example")===0){
$my_line = "example";
}
要删除数字:
$str = preg_replace("/\d/", "", "This 1 is 01 2 a 2 test 4 45 aaa");
echo $str;
输出:这是一个aaa测试
用“hello world”替换整行(仅当它以“example”开头时): 输出:
你好,世界
将两者结合在一起将使我们:
$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;
}
希望这能有所帮助。它没有起作用。这就是我所拥有的,它没有工作:It’谢谢你的麻烦!我一定是做错了什么它更改了所选行的编号。。。我应该在哪里输入我想替换的行?对不起,我的错误。我已经更新了代码,您可以更改变量$replaceWith来实现这一点。这实际上是可行的。。它已经删除了这些数字。。4.我还是做不到这一点。。我不知道在哪里输入它必须被替换的行!!我只选择要隐藏的数字。我只想要这种数字(001,002,003,004,…)有什么建议吗?是的。您可以将
/\d/
替换为/[0-9]{3}/
$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
$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;
}
?>