1

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.

5
  • Where does $server come from? Commented Dec 15, 2017 at 11:25
  • You dont even attempt to add the word ldaps to anything in this code Commented Dec 15, 2017 at 11:26
  • Whats the content of the file default? Commented Dec 15, 2017 at 11:32
  • contain text but I want to append word 'ldaps' after line which contain 'redundant LDAP {' Commented Dec 15, 2017 at 11:33
  • Can you include an example text and what you want it to look like? I think there is a much easier solution. Commented Dec 15, 2017 at 12:06

2 Answers 2

1
$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); 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.