0

假设我有一个文本:

此行是此文本的第一行,称为 %title%

这条线是第二条

第三行,%title% 不应该被替换

...

最后一行

现在我想使用 PHP,所以文本变成:

此行是此文本的第一行,名为 MY_TITLE

这条线是第二条

第三行,%title% 不应该被替换

...

最后一行

注意第三行的 %title%

最好(最快)的方法是什么?

4

3 回答 3

4

您只能将第一行加载到变量中,str_ireplace然后将第一行 + 文件的其余部分重新组合在一起。

$data = explode("\n", $string);
$data[0] = str_ireplace("%title%", "TITLE", $data[0]);    
$string = implode("\n", $data);

它不是最有效的方式恕我直言,但适合且快速编码。

于 2013-06-04T13:18:49.887 回答
4

有两种方法:

  • 如果您确定替换必须完全执行一次(即占位符将始终位于第一行,并且始终只有一个),您可以使用$result=str_replace('%title%','MY_TITLE',$input,1)

  • 如果不能保证,则需要将第一行分开:

.

$pos=strpos($input,"\n");
if (!$pos) $result=$input;
else $result=str_replace('%title%','MY_TITLE',substr($input,0,$pos)).substr($input,$pos);
于 2013-06-04T13:21:53.203 回答
3

您可以使用preg_replace()它只是一行代码;)

$str = "this line is the first line of this text called %title%\n
this line is the second one\n
the third line, %title% shouldn't be replaced\n
last line";

echo preg_replace('/%title%$/m','MY_TITLE',$str);

正则表达式的解释:

  • /%title%方法%title%
  • $表示行尾
  • m使输入的开头 (^) 和输入的结尾 ($) 代码也分别捕获行的开头和结尾

输出:

this line is the first line of this text called MY_TITLE
this line is the second one the third line, %title% shouldn't be replaced
last line
于 2013-06-04T13:25:15.997 回答