Jump to content

[SOLVED] help inserting data with php


prakash

Recommended Posts

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.

Link to comment
Share on other sites

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)

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.