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
https://forums.phpfreaks.com/topic/80863-solved-help-inserting-data-with-php/
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)

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.