php - 我如何在php中的txt中隐藏字符串中的一些单词

标签 php text show-hide words

我是 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/

相关文章:

php - 为什么 CSS 不将内容从 php echo 输出移动到 html?

php - 如何在 Vue 3 中使用 Laravel toastr 包

mysql - 为什么如果我创建一个 varchar(65535),我得到一个 mediumtext?

c# - 增强小字体可读性的文本效果

html - tumblr 预览呈现的文本样式与实际站点不同

php - 使用 jscript 显示/隐藏 div

javascript - 单选按钮+复选框组合

jquery 隐藏和显示打印

php - 如何根据用户命令字符串为 HTML 元素着色

php - 获取要在 WooCommerce 3 中显示的产品价格