M.Bwe
M.Bwe

Reputation: 159

insert text after specified string using php

I want to add text to a file after specified string using PHP.

For example, I want to add the word 'ldaps' after #redundant LDAP { string

I used this code without result:

$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); 

The only thing this code does is put lines into an array and then insert to the file without adding the word.

Upvotes: 1

Views: 1727

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94642

$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); 

Upvotes: 1

Philipp
Philipp

Reputation: 15629

Currently, you only should modify your file_put_contents code and it should work. file_put_contents expect and string, but you want to pass an array. Using join, you could combine the array to an string again.

In addition to that, you might also want to add trim to your compare, to avoid problems with spaces and tabs.

$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); 

Upvotes: 0

Related Questions