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.

Charles
  • 50,943
  • 13
  • 104
  • 142
Bounce
  • 2,066
  • 6
  • 34
  • 65
  • 3
    there is a lot of ways. if you could be do kind to provide us with certain example of both your texts and circumstances, you will get way better answer – Your Common Sense Aug 02 '10 at 13:12
  • 2
    *(related)* [find and replace keywords by hyperlinks in an html fragment, via php dom](http://stackoverflow.com/questions/3151064/find-and-replace-keywords-by-hyperlinks-in-an-html-fragment-via-php-dom/3151554#3151554) – Gordon Aug 02 '10 at 13:20

3 Answers3

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
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)
}
NullUserException
  • 83,810
  • 28
  • 209
  • 234
  • 1
    What if `$insert` breaks a HTML tag at position 1000? – Pekka Aug 02 '10 at 13:14
  • @Pekka I am assuming he/she knows exactly where things should be inserted. – NullUserException Aug 02 '10 at 13:16
  • 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 ) ? – Bounce Aug 04 '10 at 07:47
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);
Christian Smorra
  • 1,756
  • 11
  • 13