2

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

3 Answers 3

3
substr($html, 0, 1000) . $newHtml . substr($html, 1000)

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

Sign up to request clarification or add additional context in comments.

Comments

2

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)
}

3 Comments

What if $insert breaks a HTML tag at position 1000?
@Pekka I am assuming he/she knows exactly where things should be inserted.
In my case substr works pretty well. If talking about dom functions, so what function to use ? Maybe this one - DOMCharacterData::insertData( php.net/manual/en/domcharacterdata.insertdata.php ) ?
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.