StarShows Studios
StarShows Studios

Reputation: 99

How do I convert my sed insert text script in PHP?

I have a working sed script that inserts text to a document at the line number.

sed -i '35i \ NewPage,' file

wondering if theres a way i can achive the same result using php. 35 i is the row number to be inserted \ make the insert in a new line NewPage is the text being inserted file is the file location

Any suggestions? Best regards AT.

Upvotes: 1

Views: 164

Answers (1)

Akshay Hegde
Akshay Hegde

Reputation: 16997

You can but can't be oneliner like sed

Sample Input

akshay@db-3325:/tmp$ seq 1 5 > test.txt
akshay@db-3325:/tmp$ cat test.txt 
1
2
3
4
5

Output with sed at line number 4

akshay@db-3325:/tmp$ sed '4i \ NewPage,' test.txt 
1
2
3
 NewPage,
4
5

PHP Script

akshay@db-3325:/tmp$ cat test.php 
<?php
$new_contents = " NewPage,";
$file     = "test.txt";
$line     = 4;

$contents = file($file); 
array_splice($contents, $line-1, 0, $new_contents.PHP_EOL);
file_put_contents($file, implode("",$contents));
?>

Execution and Output

akshay@db-3325:/tmp$ php test.php 
akshay@db-3325:/tmp$ cat test.txt 
1
2
3
 NewPage,
4
5

OR else you have to use exec, but careful if you are enabling exec in your server, usually people disable these functions in their php.ini configuration

exec("sed -i '35i \ NewPage,' path/to/file 2>&1", $outputAndErrors, $return_value);
if (!$return_value) {
    // Alright command executed successfully 
}

Note : In general functions such as “exec” and “system” are always used to execute the external programs. Even a shell command can also be executed. If these two functions are enabled then a user can enter any command as input and execute into your server.

Upvotes: 1

Related Questions