在PHP文本的第一行用另一个单词替换出现的单词


replacing occurences of a word with another on the first line of a text in PHP

假设我有一个文本:

这一行是这个名为%title%的文本的第一行

这一行是第二行

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

最后一行

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

这一行是这个名为MY_TITLE的文本的第一行

这一行是第二行

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

最后一行

注意第三行%title%也是

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

有两种方法:

  • 如果您确定,替换必须完全完成一次(即占位符将始终在第一行,并且始终只有一次),您可以使用$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);

您可以只加载第一行到变量,然后执行str_ireplace,然后将第一行+文件的其余部分放回一起。

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

这不是最有效的方式,但适合和快速编码。

您可以使用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