【问题标题】:How to read a txt file with php and replace certain variables? [duplicate]如何用php读取txt文件并替换某些变量? [复制]
【发布时间】:2020-08-04 13:04:26
【问题描述】:

我正在尝试使用 PHP 打开、读取和呈现 .txt 文件的内容。

我想用<br> 替换所有新行\n。我可以在 <pre> 标记内回显它,但是当我尝试这种方法时,页面不再响应。

我还想用不同的变量替换上面提到的 { name }$name,例如 python fstrings 的工作原理。

我目前有这个:

echo file_get_contents("file.txt");

这将产生如下所示的东西:

Line1, Line2, Line3, Line4 { Person1 }

我如何让结果看起来像这样

Line1,
Line2,
Line3,
Line4 James

【问题讨论】:

标签: php file


【解决方案1】:

,不能将其视为 f-string,因为没有内置函数来评估 f-string。但是,您可以使用str.format 方法格式化内容。喜欢:

name = 'Person Name'
readFile = input('Txt File: ')
file = open(readFile, 'r')
content = file.read()
print(content.format(**locals()))
file.close()
你好人名 2号线

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多