Writing to a file with start and end

Published 6 days ago by dk4210

Hello guys,

This i mainly a PHP question.

I have a file that contains two comments

#start

#end

I would like to search in the file and find the #start and #end tags and replace whatever is between it with custom content.

Here's the code I have so far. This will only replace one line though, which is the #start line only. I need it to replace between the two comments.

$filename = (public_path('/../tests/Browser/mytest.txt'));

    $find = "#start";
    $replace = "whatever";
    $file = $filename;
    $contents = file_get_contents($file);
    $contents = str_replace($find,$replace,$contents);
    file_put_contents($file,$contents);

Please advise

Thanks!

Best Answer (As Selected By dk4210)
burlresearch

sounds like a job for preg_replace:

$replace = 'whatever';
$replacement = "#start\n{$replace}\n#end\n";
$output = preg_replace("/#start.*#end\s+/sm", $replacement, $contents);
jlucia
jlucia
6 days ago (20,150 XP)

Is there any reason you need a start and end comment?

Just replace a single comment with your custom content. Maybe name it #placeholder or whatever you like, it should still just replace what you need.

dk4210
dk4210
6 days ago (13,420 XP)

Yea I need it between the two placeholders, due to there being code that should not be changed under the #end placeholder.

jlucia
jlucia
6 days ago (20,150 XP)

I don't think it would be changed under a single comment. It is just a simple find and replace. It should only add what you want to that one line and leave the text above and below it alone.

burlresearch

sounds like a job for preg_replace:

$replace = 'whatever';
$replacement = "#start\n{$replace}\n#end\n";
$output = preg_replace("/#start.*#end\s+/sm", $replacement, $contents);
dk4210
dk4210
6 days ago (13,420 XP)

Thanks! I will give it a try.

dk4210
dk4210
5 days ago (13,420 XP)

@burlresearch dude your'e awesome! It worked like a champ. Here's my final code. In hopes it will help others

    $file = $filename;
    $replace = $tcontent2;
    $replacement = "#start\n{$replace}\n#end\n";
    $contents = file_get_contents($file);
    $output = preg_replace("/#start.*#end\s+/sm", $replacement, $contents);
    file_put_contents($file,$output);

burlresearch

nice, glad it helped - regular expressions can do magic!

dk4210
dk4210
5 days ago (13,420 XP)

I have to get better with Regex.

Please sign in or create an account to participate in this conversation.