prakash Posted December 9, 2007 Share Posted December 9, 2007 how can I insert some stuffs between random line of a string which have multiple line value for example $string=" some text line1 some text line2 some text line3 some text line4 some text line5"; $insertvalue="some code here"; so I want to add $insertvalue data on one of the line of $string randomly each time page is requested. Quote Link to comment https://forums.phpfreaks.com/topic/80863-solved-help-inserting-data-with-php/ Share on other sites More sharing options...
Aureole Posted December 9, 2007 Share Posted December 9, 2007 Wait, you want to add $insertvalue onto the end of $string, right? If so... <?php $string = 'blah'; $insertvalue = 'blah'; $string .= $insertvalue; echo($string); // Output: blahblah ?> I think that's what you asked for... Quote Link to comment https://forums.phpfreaks.com/topic/80863-solved-help-inserting-data-with-php/#findComment-410220 Share on other sites More sharing options...
prakash Posted December 9, 2007 Author Share Posted December 9, 2007 Wait, you want to add $insertvalue onto the end of $string, right? If so... <?php $string = 'blah'; $insertvalue = 'blah'; $string .= $insertvalue; echo($string); // Output: blahblah ?> I think that's what you asked for... above will add $insertvalue to the last line but my question is that how to add the same to random line (not the first or last line) Quote Link to comment https://forums.phpfreaks.com/topic/80863-solved-help-inserting-data-with-php/#findComment-410223 Share on other sites More sharing options...
GingerRobot Posted December 9, 2007 Share Posted December 9, 2007 How's about: <?php $str="line1 line2 line3 line4"; $insert = "new line"; $lines = explode("\n",$str); $num = count($lines); $insert_after = mt_rand(0,count($lines)-1); $new_str = ''; foreach($lines as $k => $v){ $new_str = $new_str."\n".$v; if($k==$insert_after){ $new_str = $new_str."\n".$insert; } } echo nl2br($new_str); ?> Quote Link to comment https://forums.phpfreaks.com/topic/80863-solved-help-inserting-data-with-php/#findComment-410228 Share on other sites More sharing options...
prakash Posted December 9, 2007 Author Share Posted December 9, 2007 thx for the solution Quote Link to comment https://forums.phpfreaks.com/topic/80863-solved-help-inserting-data-with-php/#findComment-410231 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.