[英]How to change the HTML page title dynamically generated by PHP code
My PHP code is generating 495 HTML pages from 495 txt files and working correctly. 我的PHP代码从495个txt文件生成了495个HTML页面,并且工作正常。 But right now, I'm trying to change it as a way to change the value of title tag dynamically;
但是现在,我正在尝试更改它,以动态更改title标签的值。 so I'm trying to replace
%TITLE%
with $Oneline
that is the first line of each txt pages. 因此,我试图用
$Oneline
替换%TITLE%
, $Oneline
是每个txt页面的第一行。
I have tried many syntaxes such as prg_replace
, str_replace
and much more all seems unsuccessful. 我尝试了许多语法,例如
prg_replace
, str_replace
,而且似乎都失败了。 In fact those lines of codes change nothing on my HTML pages. 实际上,这些代码行在我的HTML页面上没有任何变化。
To be more clear: 更清楚地说:
%TITLE%
with $Oneline
. %TITLE%
替换为$Oneline
。 $Oneline
is the first line of the txt file. $Oneline
是txt文件的第一行。 Thanks for any help. 谢谢你的帮助。
<?php
for ($i = 1; $i <= 495; $i++)
{$j = 1;
$SousrceFile = @fopen($SousrceFile, 'r') ;
$TargetFile = fopen($TargetFile, 'w+') ;
fwrite($TargetFile, "<title>%TITLE%</title>\n");
while ($Oneline = @fgets($SousrceFile, 4096))
{$j = $j + 1;
if (strlen($Oneline) !==0)
{
$title = $Oneline;
$newTitle = preg_replace('%TITLE%', $title, $newTitle,1 );
...?>
Please take a look at preg_replace()
, the parameters are 请看一下
preg_replace()
,参数是
preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
In your code you are using the variable $title
to replace the pattern in $newTitle
with a limit of one. 在您的代码中,使用变量
$title
限制$newTitle
的模式为1。 I think you want to replace the text in the target file instead. 我认为您想替换目标文件中的文本。
Update: There are two solutions that come into my mind right now: 更新:我现在想到两种解决方案:
preg_replace()
and you can change your title dynamically. preg_replace()
搜索此变量,并且可以动态更改标题。 After you done that, write the variable into the targe file by eg fputs()
. fputs()
将变量写入目标文件。 I would recommend solution one. 我建议解决方案一。 You know how to do that?
你知道怎么做吗?
据我所知,$ newTitle没有在pre_replace之前定义。
After I couldn't solve the problem, I moved the retreiving data loop to above of the title
and as Aaron suggested at this post It made it quiet simple as bellow: 在我解决不了问题之后,我将检索数据循环移到
title
上方,并且正如亚伦在这篇文章中所建议的那样,这使得它的安静变得简单如波纹管:
<?php
for ($i = 1; $i <= 495; $i++)
{$j = 1;
$SousrceFile = @fopen($SousrceFile, 'r');
$TargetFile = fopen($TargetFile, 'w+');
while ($Oneline = @fgets($SousrceFile, 4096))
{$j = $j + 1;
if (strlen($Oneline) !==0)
$title = $Oneline;
fwrite($TargetFile, "<title>{$title}</title>\n");
...?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.