Insert a line between two points using PHP

How to insert text between two comments, as shown below with PHP. Thanks in advance.

<!-- BEGIN INSERT 1 --> <!-- END INSERT 1 --> 
+3
source share
4 answers

Maybe just paste after the first tag?

 $afterinsert = str_replace( "INSERT 1 -->" , "INSERT 1 -->\n".$toinsert , $beforeinsertion ); 

If you want to insert only with both tags, use preg_replace.

+1
source
 $after = preg_replace( "/<!-- BEGIN INSERT 1 -->\s*<!-- END INSERT 1 -->/", "<!-- BEGIN INSERT 1 -->".$insert."<!-- END INSERT 1 -->", $before); 
+5
source

a little more context may be helpful. it could be that simple:

 <!-- begin insert 1 --> <?php echo 'text to be inserted'; ?> <!-- end insert 1 --> 

what are you trying to do?

+3
source

This will do the job. It uses substr_replace() . You can learn more about this here .

 <?php $stringToInsert = "tesssst"; $oldString = "<!-- BEGIN INSERT 1 --><!-- END INSERT 1 -->"; $newString = substr_replace($oldString, "-->" . $stringToInsert . "<!--", strpos($oldString, "--><!--"), strlen($stringToInsert)); 
0
source

All Articles