Jump to content

Create String Problem


The Little Guy

Recommended Posts

I need the code below to remove all lines after the 5 line of code that is placed in a textarea, but that isn't happening.

 

PHP Code:

<?php
    $expl = preg_split("~\n~",addslashes($_POST['ids']),5);
    $impl = implode(";",$expl);
    $impl = preg_replace("~\r~","",$impl);
    print_r($expl);
    echo '<p> </p>';
    echo '<p> </p>';
    echo $impl;
?>

 

As you can see, after the code runs, it does this and if there are any remaining lines of code, it still adds them to the array but it does it wrong. What I would like, is that it doesn't even add it to the array, but to drop it after the 5 line is inserted.

 

Source Code Results:

Code:

 

Array 
( 
    [0] => 250122680617 
    [1] => 270124543912 
    [2] => 220116609171 
    [3] => 170117303591 
    [4] => 160123241047 
220118409806 
) 

250122680617;270124543912;220116609171;170117303591;160123241047 
220118409806

 

In the array above you can see the last line doesn't have a key value associated with it, that value I want to be removed from the array.

Link to comment
https://forums.phpfreaks.com/topic/54154-create-string-problem/
Share on other sites

<?php
    $expl = split("\r\n",addslashes($_POST['ids'])); // split it at new line carriage.
    if (!is_array($expl)) {
          $expl = split("\n",addslashes($_POST['ids'])); // split it at new line.
    }

    $impl = implode(";",$expl[0]); // implode the first element of the expl array returned as that houses our ids.
    echo 'Explode Array: <pre>',print_r($expl), '</pre>';
    echo '<p> </p>';
    echo '<p> </p>';
    echo 'Implode Array: <pre>',print_r($impl),'</pre>';
?>

 

See where that gets ya.

Link to comment
https://forums.phpfreaks.com/topic/54154-create-string-problem/#findComment-267721
Share on other sites

Thank you guys, but I just got an Idea, I decided to do a for loop and and implode/explode it at double semi colons, then trim the remaining ones off.

 

final result:

<?php
    $expl = split("\r\n",addslashes($_POST['ids'])); // split it at new line carriage.
    if (!is_array($expl)) {
          $expl = split("\n",addslashes($_POST['ids'])); // split it at new line.
    }
$count = count($expl);
$i = 0;
foreach($expl as $val){
	if($i<5){
		$impl .= ';'.$val.';';
	}else{
		break;
	}
	$i++;
}	
?>

Link to comment
https://forums.phpfreaks.com/topic/54154-create-string-problem/#findComment-267881
Share on other sites

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.