Insert string between two points with PHP

2020-03-04 12:15发布

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

<!-- BEGIN INSERT 1 -->

<!-- END INSERT 1 -->

标签: php html
4条回答
Luminary・发光体
2楼-- · 2020-03-04 12:37

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?

查看更多
Deceive 欺骗
3楼-- · 2020-03-04 12:41

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.

查看更多
够拽才男人
4楼-- · 2020-03-04 12:42
$after = preg_replace(
    "/<!-- BEGIN INSERT 1 -->\s*<!-- END INSERT 1 -->/",
    "<!-- BEGIN INSERT 1 -->".$insert."<!-- END INSERT 1 -->", 
    $before);
查看更多
做个烂人
5楼-- · 2020-03-04 12:58

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));
查看更多
登录 后发表回答