PHP replacing lines in a small paragraph from a big paragraph - php

I have 2 bulks of text: Trunk, and Card. Trunk has about 100 lines, and Card has 3. The 3 lines in Card exist in Trunk, but they aren't directly below eachother.
What I'm trying to do is remove each line of Card from the string Trunk.
What came to mind is exploding Card into an Array and using a for each in loop, like in AS3, but that didn't work like planned. Here's my attempt:
$zarray = explode("\n", $card); //Exploding the 3 lines which were seperated by linebreaks into an array
foreach ($zarray as $oneCard) //for each element of array
{
$oneCard.= "\n"; //add a linebreak at the end, so that when the text is removed from Trunk, there won't be an empty line in it.
print "$oneCard stuff"; //Strangely outputs all 3 elements of the array seperated by \r, instead of just 1, like this:
//card1\rcard2\rcard3 stuff
$zard = preg_replace("/$oneCard/i", "", $trunx, 1);//removes the line in Card from Trunk, case insensitive.
$trunx = $zard; //Trunk should now be one line shorter.
}
So, how can I use the foreach loop so that it replaces properly, and uses 1 element each time, instead of all of them in one go?

Consider
$trunk = "
a
b
c
d
e
f
";
$card = "
c
e
a
";
$newtrunk = implode("\n", array_diff(
explode("\n", $trunk),
explode("\n", $card)
));
print $newtrunk; // b d f
Or the other way round, your wording is a bit unclear.

Try this, it will be faster than the preg_replace due to the small amount being replaced:
//Find the new lines and add a delimiter
$card = str_replace("\n", "\n|#|", $card);
//Explode at the delimiter
$replaceParts = explode('|#|', $card);
//Perform the replacement with str_replace and use the array
$text = str_replace($replaceParts, '', $text);
This assumes there is always a newline after the search part and you do not care about case sensitivity.
If you do not know about the new line you will need a regex with an optional match for the newline.
If you need it case sensitive, look at str_ireplace

You could explode the $card, and keep the $trunk as string:
$needlearray = explode("\n", $card); //to generate the needle-array
$trunk = str_replace($needlearray,array(),$trunk); //replace the needle array by an empty array => replace by an empty string (according to the str_replace manual)
$trunk = str_replace("\n\n","\n",$trunk); //replace adjacent line breaks by only one line break

Related

TextArea to Array with PHP

I'm trying to figure out how to convert html textarea into php array,
I've used a form with POST to deliver the query to the php script,
and the php file is getting them with the following line:
$ids = array($_POST['ids']);
Needless to say that it puts everything into one line
Array ( [0] => line1 line2 line3 line4 )
I need the final results to replace this:
$numbers = array(
"line1",
"line2",
"line3",
"line4"
);
What would be the best approach to divide and re-parse it ?
Using an explode on \n is a proper way to get new lines. keep in mind though that on some platforms the end of line is actually send by \r\n, so just exploding on \n could leave you with extra data on the end of each line.
My suggestion would be to remove the \r before exploding, so you dont have to loop through the entire array to trim the result. As a last improvement, you dont know that there actually is a $_POST['ids'], so always check it first.
<?
$input = isset($_POST['ids'])?$_POST['ids']:"";
//I dont check for empty() incase your app allows a 0 as ID.
if (strlen($input)==0) {
echo 'no input';
exit;
}
$ids = explode("\n", str_replace("\r", "", $input));
?>
I would've done the explode by Hugo like this:
$ids = explode(PHP_EOL, $input);
manual Predefined Constants
Just my two cents...
Use this
$new_array = array_values(array_filter(explode(PHP_EOL, $input)));
explode -> convert textarea to php array (that lines split by new line)
array_filter -> remove empty lines from array
array_values -> reset keys of array
If the textarea simply has line breaks per entry then I'd do something like:
$ids = nl2br($_POST['ids');
$ids = explode('<br />',$ids); //or just '<br>' depending on what nl2br uses.
Try with explode function:
$ids = $_POST['ids']; // not array($_POST['ids'])
$ids = explode(" ", $ids);
The first parameter is the delimiter which could be space, new line character \r\n, comma, colon etc. according to your string from the textarea (it's not clear from the question whether values are separated by spaces or by new lines).

PHP preg_replace replacing line break

When renumbering an array using
$arr=array_values($arr); // Renumber array
I realized that a line break is being introduced into one of the array strings, which I don't want.
My string is going from:
Property
Type
to Property
Type
In any case I am using:
$newelement = preg_replace("/[^A-Za-z0-9\s\s+]/", " ", $element);
already to remove unwanted characters prior to database insertion, so I tried to change it to:
$newelement = preg_replace("/[^A-Za-z0-9\s\s+'<br>''<br>''/n''/cr']/", " ", $element);
But there is no change, and the ?line feed/line break/carriage return is still there.
Am I doing the preg_replace call correctly?
That preg looks a bit complicated. And then you have ^ in the beginning as not A-Z... or linefeed. So you don't want to replace linefeed?
How about
$newelement = preg_replace("/[\n\r]/", "", $element);
or
$newelement = preg_replace("/[^A-Za-z ]/", "", $element);
\s also matches linefeed (\n).
This should work too:
// char(32) is whitespace
// For CR
$element = strtr($element, chr(13), chr(32));
// For LF
$element = strtr($element, chr(10), chr(32));
This thing worked for me.
preg_replace("/\r\n\r\n|\r\r|\n\n/", "<br />", $element);
It's a hack, but you can do something like this:
$email_body_string = preg_replace("/\=\r\n$/", "", $email_body_string);
The replacement says find a line that ends with an equals sign and has the standard carriage return and line feed characters afterwards. Replace those characters with nothing ("") and the equals sign will disappear. The line below it will be pulled up to join the first line.
Now, this implies that you will never have a line that ends with an equals sign, which is a risk. If you want to do it one better, check the line length where the wrap (with the equals sign) appears. It's usually about 73 characters in from the beginning of the line. Then you could say:
if (strlen(equals sign) == 73)
$email_body_string = preg_replace("/\=\r\n$/", "", $email_body_string);

How to input text into a php array based on the text formatting

I have a text document that is opened and read by php that looks like this
ABC: 123
DEF: 456
GHI: 789
So basically it is one piece of text ended with a colon, followed by another piece of text. To separate the lines there is a line break (i.e. " \n ")
Is it possible to have this go into an array separated by the colon and the line break? So that when I print the value it should look like this:
" ABC:123,DEF:456,GHI:789 "
First thing you need to do is split those lines up.
$lines = explode("\n", $doctext);
Next, process those lines one-by-one, splitting out the appropriate values.
$output = array();
foreach ($lines as $line) {
$line_parts = explode(': ', $line, 2); // Limit 2, in case data contains a colon
$output[$line_parts[0]] = $line_parts[1];
}
Then, you can find your array in $output. Note that you should also add some validation to these lines and what not, to make sure they contain the data you expect. Also, if the lines optionally contain a space between the colon and the value, or a variable amount of whitespace, then split on the colon and use trim() on the value, as appropriate.

preg_split - New Line

I'm currently developing a script that takes a message, splits it apart every 100 characters or so, and sends each part.
However, my original string has "\n" lines in it, and this is causing an issue with my preg_split, causing it to split pre-maturely (e.g., before 100 characters).
Here's what I am currently working with:
$sMessage = "Msg from John Smith \n".
"SUBJ: Hello! \n".
"This is the bulk of the message and can be well over 200 or 300 characters long. \n".
"To reply, type R 131, then ur msg.";
$split = preg_split('/(.{0,100})\s/',
$sMessage,
0,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
array_shift($split);
$count = count($split);
foreach ($split as $key => $message) {
$part = sprintf("(%d/%d) %s", $key+1, $count, $message);
echo $part;
echo "<br>";
}
Now, with this, I've noticed 3 things:
1) The first part of the message ("Msg from John Smith") does not even get included in the array.
2) The new lines (\n) seem to cut the string early.
3) Oddly enough, with the last line of the message ("To reply" etc...) it cuts off the last word ("msg.") and adds that into a new line, no matter what the sentence may read.
Any help on this would be great!
You are actually trying to reimplement the function wordwrap(). I think the call that does the job you need would look like this:
$array = explode("\n", wordwrap($string, 100, "\n", true));
my original string has "\n" lines in it
Use the PCRE_DOTALL modifier to allow ‘.’ to match newlines.
Chunking a string into an array of fixed-length strings can more easily be done using str_split. As soulmerge suggests, wordwrap is probably better if that's what you're really trying to do. You can use explode to split a string out to an array afterwards.
Avoid resorting to regex where string processing functions are available. (And PHP has a lot.)

Delete first four lines from the top in content stored in a variable

I have a variable that needs the first four lines stripped out before being displayed:
Error Report Submission
From: First Last, email#example.com, 12345
Date: 2009-04-16 04:33:31 pm Eastern
The content to be output starts here and can go on for any number of lines.
I need to remove the 'header' from this data before I display it as part of a 'pending error reports' view.
Mmm. I am sure someone is going to come up with something nifty/shorter/nicer, but how about:
$str = implode("\n", array_slice(explode("\n", $str), 4));
If that is too unsightly, you can always abstract it away:
function str_chop_lines($str, $lines = 4) {
return implode("\n", array_slice(explode("\n", $str), $lines));
}
$str = str_chop_lines($str);
EDIT: Thinking about it some more, I wouldn't recommend using the str_chop_lines function unless you plan on doing this in many parts of your application. The original one-liner is clear enough, I think, and anyone stumbling upon str_chop_lines may not realize the default is 4 without going to the function definition.
$content = preg_replace("/^(.*\n){4}/", "", $content);
Strpos helps out a lot: Here's an example:
// $myString = "blah blah \n \n \n etc \n \n blah blah";
$len = strpos($myString, "\n\n");
$string = substr($myString, $len, strlen($myString) - $len);
$string then contains the string after finding those two newlines in a row.
Split the string into an array using split(rex), where rex matches two consecutive newlines, and then concatenate the entire array, except for the first element (which is the header).

Categories