使用php在指定字符串后插入文本

使用php在指定字符串后插入文本,php,file-put-contents,Php,File Put Contents,我想使用PHP将文本添加到指定字符串之后的文件中 例如,我想在#redundant LDAP{字符串之后添加单词'ldaps' 我使用了此代码,但没有结果: $lines = array(); foreach(file("/etc/freeradius/sites-enabled/default") as $line) { if ("redundant LDAP {" === $line) { array_push($lines, 'ldaps'); }

我想使用PHP将文本添加到指定字符串之后的文件中

例如,我想在
#redundant LDAP{
字符串之后添加单词'ldaps'

我使用了此代码,但没有结果:

$lines = array();
foreach(file("/etc/freeradius/sites-enabled/default") as $line) {
    if ("redundant LDAP {" === $line) {
        array_push($lines, 'ldaps');
    }
    array_push($lines, $line);
}
file_put_contents("/etc/freeradius/sites-enabled/default", $lines); 

此代码所做的唯一事情是将行放入数组中,然后插入到文件中,而不添加单词。

当前,您只需修改
文件的内容
代码,它就可以工作。
文件的内容
期望和字符串,但您希望传递数组。使用
连接
,您可以将数组又是一根绳子

除此之外,您可能还希望在比较中添加修剪,以避免空格和制表符出现问题

$lines = array();
foreach(file("/etc/freeradius/sites-enabled/default") as $line) {
    // should be before the comparison, for the correct order
    $lines[] = $line;
    if ("redundant LDAP {" === trim($line)) {
        $lines[] = 'ldaps';
    }
}
$content = join("\n", $lines);
file_put_contents("/etc/freeradius/sites-enabled/default", $content); 

$server
从何而来?您甚至都不会尝试将单词
ldaps
添加到此代码中的任何内容文件的内容
default
?包含文本,但我想在包含“冗余LDAP”的行后添加单词“ldaps”{您能提供一个示例文本以及您希望它看起来像什么吗?我认为有一个更简单的解决方案。
$lines = array();

foreach(file("/etc/freeradius/sites-enabled/default") as $line)) {
    // first switch these lines so you write the line and then add the new line after it

    array_push($lines, $line);

    // then test if the line contains so you dont miss a line
    // because there is a newline of something at the end of it
    if (strpos($line, "redundant LDAP {") !== FALSE) {
        array_push($lines, 'ldaps');
    }
}
file_put_contents("/etc/freeradius/sites-enabled/default", $lines);