Here we have the code, let's say (the text in $ var may change and other tags may appear there, not just the 'a', but maybe they will not be there at all):

$var = "slovo <a href='hashcode.ru'>slovo</a> slovo"; echo substr_replace($var, 'bob', 8, 0) . "<br />\n"; 

As a result, substr_replace will break the html tag "a" and fit into it. Such porridge will turn out:

 slovo <abobashcode.ru'>slovo</a> slovo<br /> 

How to do to temporarily remove the formatting from the text, and then, when substr_replace finishes, put back all the formatting tags. Simply put, how to get this result:

 slovo <a href='hashcode.ru'>slovo</a>bob slovo 

Note: you need to insert text after the closing html tag, whatever it is.

    3 answers 3

    Try to do this:

     $var = "slovo"; $slovo = substr_replace($var, 'bob', 1, 0); echo "$var <a href='hashcode.ru'>$slovo</a> $var"; 
    • the text in $ var may change and other tags may appear there, not just the 'a', but maybe they will not be there at all - nick777

    And why don't you start by not finding the position of the entry of the given word ("bob") in the source line, using the "strpos ()" function, and then using the "substr_replace ()" function:

     $var = "slovo <a href='hashcode.ru'>slovo</a> slovo"; $pos = strpos($var,"bob"); echo substr_replace($var, 'bob', $pos, mb_strlen("bob")) . "<br />\n"; 

      Because I needed it for Wordpress, then I found a solution among those already ready:

       the_excerpt(); 

      Still, as an option, you can use explode with paragraph splitting. And in the end of the first paragraph insert the desired text, then replace the new text with the old one.