usertest
usertest

Reputation: 27628

Insert string between two points with PHP

How would I insert text between two comments like the ones below with PHP. Thanks in advance.

<!-- BEGIN INSERT 1 -->

<!-- END INSERT 1 -->

Upvotes: 3

Views: 2684

Answers (4)

Bogdan Constantinescu
Bogdan Constantinescu

Reputation: 5356

This will do the job. It's using substr_replace(). You can read more about it here.

<?php

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

Upvotes: 0

h3r2on
h3r2on

Reputation: 389

a little more context might be helpful. it could be as easy as:

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

what are you trying to do?

Upvotes: 3

opatut
opatut

Reputation: 6864

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

Upvotes: 6

Piotr M&#252;ller
Piotr M&#252;ller

Reputation: 5548

Maybe just insert after first tag ?

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

If you want to insert only when there are both tags, use preg_replace.

Upvotes: 2

Related Questions