tags:

views:

59

answers:

3

Hi,

is there any function to insert string1 into another string2 if known particular insert place of string2. For example I have HTML code about 2000 chars long. And at 1000 char I want to insert other string which is 200 chars length.

Your help would be appreciated.

+2  A: 

Something like this would work:

$newstr = substr($str, 0, 1000) . $insert . substr($str, 1000)

Made into a function

function insertAt($str, $position, $toInsert) {
    return substr($str, 0, $position) . $toInsert . substr($str, $pos)
}
NullUserException
What if `$insert` breaks a HTML tag at position 1000?
Pekka
@Pekka I am assuming he/she knows exactly where things should be inserted.
NullUserException
In my case substr works pretty well. If talking about dom functions, so what function to use ? Maybe this one - DOMCharacterData::insertData( http://www.php.net/manual/en/domcharacterdata.insertdata.php ) ?
+2  A: 
substr($html, 0, 1000) . $newHtml . substr($html, 1000)

But actually, that sounds like a really fragile idea. You should rather use DOM processing methods.

deceze
+1  A: 

use wildcards at the place you want to insert code

$html="<div>%%wildcard%%</div>"

and use str_replace

$new_html=str_replace('%%wildcard%%', 'i like cookies', $html);
Christian Smorra