Php Split text from html text area - php

I am trying to split a string that i pass from a HTML textarea.
Enter the list of Ids: <textarea rows="4" cols="50" name="ids">
I get it in a php script as
$idlist=$_GET["ids"];
When I try to split it, I couldnt get it with explode. Tried out with multiple delimitiers that could possibly split this and then tried using preg_split. I gave this as my regex.
$ids=preg_split("/\s/",$idlist);
Now that i split, I get empty array elements in the $ids. And I couldnt match them like
$ids[$i]==""|" "|"\s"
1) How will the text in text area be passed? I am giving one Id per line in the text area. It doesnt not carry new line character but a single space.
2) Will preg_split split out even the delimitiers that one uses to split the string?
I know I am making a blunder but couldnt figure out where. Someone any thoughts?

If each ID is on a new line, you need to explode by the new line character \n...
$ids=preg_split("/\r|\n)*/", $idlist);
EDIT: Updated to support windows encoding due to it being sent as a GET not a POST..
Explanation:
Windows send new lines as \r\n so if it is a GET the you need to provide support for this...

Here you go - just using explode to break them down into an array based on the "\n" new line character. I know you mentioned this does not work, but tested it and it works fine for me:
<?php
if (isset($_GET['ids'])) {
$arrayOfIds = explode("\n", $_GET['ids']);
}
?>
<form method="get" action="">
<textarea name="ids"></textarea>
<button type="submit">Submit</button>
</form>
As you mentioned above, when typing ID's into the textarea field I just put them each on a new line.

Figured it out. There was a single space as well as a New line character in the string. Exploded it with \n and then trimmed it with trim() that solved the problem.

With a textarea you have to assume the user is stupid when you ask them to provide data. If you say "Provide an id on each line" assume they will not read it and use commas or assume they press ENTER 50 times at the end, or assume they pasted it in from MS Word. No offense to the user, but just assume they are a Jelly fish on a keyboard and at some point it manages to click "submit".
Taking that into account, (and I'm assuming here that your ids are numbers) it means that anything that isn't a number can be ignored. This makes worrying about new lines, be that \n\r or whatever, completely irrelevant as long as there is some kind of character between each id then that's all we need.
I'm going to change $_GET["ids"] to $_POST["ids"] because I'd be posting that sort of data.
// This will create a list of ids with NO care about what delimeter
// the user used regardless of what you'd requested.
// Replace all non-numeric characters with #
$ids = preg_replace("/[^0-9]/is","#",$_GET["POST"]);
// Remove recursive # and trim
$ids = preg_replace("/#{1,}/is","#",trim($ids,"#"));
// Create array ensuring ids isn't empty
// This also removes unique id entries
$ids = empty($ids)?array():array_unique(explode("#",$ids));
// Show array
echo "<pre>";
print_r($ids);
echo "</pre>";

Related

Removing spaces from a selected mysql field using PHP

I need to select a field in mysql and put it in a hidden text field so i can select it into another file. The problem is, the name of the field has spaces in it, so it gets a little buggy. It's something like this:
$GetArea = $_GET['area'];
Then i add this into a hidden textbox:
<INPUT id=txtArea type=hidden value=".$GetArea." name=txtArea />
But it doesn't read the area when i open the site, because the area name is "Area 123" with spaces. This might be a duplicate, but searching around i really couldn't find the answer. Anyone knows of a way to remove the spaces?
To answer your direct queston of how to remove spaces from a variable: Use Regex,
$GetArea = $_GET['area'];
/// = Area 123.
$GetArea = preg_replace("/\s+/","",$_GET['area']);
/// = Area123
View a regex101 example. Regex is far better than using str_replace as in one line it can handle multiple whitespace generating characters (such as the tab character or new line breaker).
However if [in another situation] you want to preserve the spaces and record them you can substitute them for something else such as a _ character:
$GetArea = $_GET['area'];
/// = Area 123.
$GetArea = preg_replace("/\s+/","_",$_GET['area']);
/// = Area_123
The above example means that when you send the data back to the database you can do a preg_replace search and replacement for all _ characters substituted into replace the space character, as needed. (although MySQL only accepts spaces in Column names when properly encased in backticks).
BUT
I would also strongly suggest you get into a habit of encasing your HTML into quotes (single usually) rather than just hanging them out as they are, as this is the principle cause of your issue. so to quote your HTML:
print "<INPUT id='txtArea' type='hidden' value='".$GetArea."' name='txtArea' />";
/** I made an assumption from your syntax your HTML was being printed by PHP **/
This means that you can keep your spaces in your data value of the HTML input element because the whole value section is defined and clearly wrapped in single quote marks.
On a broader note, you really should be looking at not using $_GET and instead transfering data page-to-page with $_POST. Also please research SQL injection and how to prevent it as well as Cross Site Scripting and how to mitigate that. Spaces in MySQL column names is a good habit to avoid.
You should probably use something like this :
$str= str_replace(' ', '', $str);

Is there a typo in this str_replace code? / Am I reading it correctly?

Here is the line of code from a PHP file, specifically it is from zstore.php which is a file include as part of the "Zazzle Store Builder" toolset from Zazzle.com
The set of files allows someone like me, who has products for sale on Zazzle and massage that data into a nicer "storefront" which I can set up my way instead of being confined by the CMS structure of Zazzle.com where they understandably want to keep the monkeys (uhmmm... users like myself) from causing too much mayhem.
So... here is the code:
$keywords = str_replace(" ",",",str_replace(",","",$keywords));
Two questions:
Am I understanding what it does and
Is there an extra single or double quote in the string that does not need to be there?
Here is what I think the line of code is saying:
Take the string of characters that the user inputs (dance diva) and assign it to the variable called
$keywords
then run the following function on that character string
= str_replace
(" ","," <<< look for spaces. If you find a space, replace it with a comma
,str_replace(",","" <<< this is the bit I don't understand or which may have a typo
I THINK that it is saying " if you find commas, leave them alone, but I'm not certain.
,$keywords)); <<< then put the edited string of characters backing to the variable called $keywords.
What lead me to look at this was that I was inputting the following:
dance,diva which is what I THOUGHT the script was wanting from me based on the commented text in the README.txt file:
// Search terms. Comma separated keywords you can use to select products for your store
So..
Am I understanding what this line of code is supposed to do?
which, assuming I am correct, and I'm pretty sure that the first half is supposed to work as I've described, now brings me to my second question:
Why isn't the second bit working? Is there a typo?
To review:
dance diva produces results
dance,diva does not
Both, SHOULD work.
Thanks in advance for your help. I have a lot of HTML experience and computer experience but PHP is new to me.
$keywords = str_replace(" ",",",str_replace(",","",$keywords));
You can split into
$temp = str_replace(",","",$keywords);
$keywords = str_replace(" ",",",$temp);
First it replaces all comas with empty string, it is removes all comas. Then replaces all spaces with comas.
For "dance diva" there are no comas so first does nothing, then it replaces space and result is "dance,diva"
For "dance,diva" it removes coma, you get "dancediva" and there in no space to replace next so it is Your result.

Newline Conversion in Submitted Text in PHP

I have a system set up for users to submit their articles into my database. Since it will just be HTML, I don't want to expect them to know to type <br /> every time there's a newline, so I am using the PHP function nl2br() on the input.
I'm also providing an article modification tool, which will bring their articles back into the form (this is a different page, however) and allow them to edit it. In doing this, the <br /> elements were appearing also (with newlines still). To remedy the elements appearing (which I had expected, anyway) I added preg_replace('/<br(\s+)?\/?>/i', "\n", mysql_result($result,$i,"content")) which I had found in another question on this site. It does the job of removing the <br /> elements, but since it is replacing them with newlines, and the newlines would have remained originally anyway, every time the post is edited, more and more newlines will be added, spacing out the paragraphs more and more each time. This is something a user won't understand.
As an example, say I enter the following into the article submission form:
Hello, this is my article.
I am demonstrating a new line here.
This will convert to:
Hello, this is my article.<br />
I am demonstrating a new line here.
Notice that, even though the newline character was converted, there is still a newline in the text. In the editing form, the <br /> will be converted back to newline and look like this:
Hello, this is my article.
I am demonstrating a new line here.
Because the <br /> was converted to a newline, but there was already a newline. So I guess what I'm expecting is for it to originally be converted to something like this:
Hello, this is my article.<br />I am demonstrating a new line here.
I'm wondering ... is there a way to stop the nl2br() function from maintaining the original newlines? Might it have to do with the Windows \r\n character?
The function you're using, nl2br is used for inserting them, but not replacing them. If you want to replace \n with <br /> you just need to use str_replace. Like so:
$string = str_replace("\n","<br />",$string);
There is absolutely no need for regex in this situation.
It seems like the problem you described is not a bug, but a feature of bl2br. You could just write your own function for it, like:
<?php
function NlToBr($inString)
{
return preg_replace("%\n%", "<br>", $inString);
}
?>
I found this one in the comments of the documentation of the nl2br-function in the PHP Manual: http://php.net/manual/de/function.nl2br.php. If the one I posted did not work for you, there should be plenty more where it came from.
(Or just use the function from the other Answer that was just posted, I guess that should work, too)
This should fix it:
preg_replace('/<br(\s+)?\/?>(?!\s*\n)/i', "\n", mysql_result($result,$i,"content"))
You cannot simply remove the breaks, because they might be on the same line. This regex will replace all breaks with newline but not those that are followed by the newline.
It will leave the <br>\n in the text. Additional regex will get rid of them:
preg_replace('/<br(\s+)?\/?>/i', "", $res)

Use line-break as separator for an array input?

I've never actually used arrays before, as I've never had to so far (a simple variable has been enough for me), however now I've created a form with a text-area that is meant to POST multiple urls through to my PHP script.
What I want to do is use a line-break in the visitors input to act as a separator for an array input.
For example, the visitor inputs 90 lines of text (all url's), the array breaks each one into a list of 90, and creates an array value for each one.
Any info, advice or comments would be greatly appreciated :)!
Not 100% percent sure what line breaks are used, e.g.:
Windows uses \r\n
Linux uses \n
(old) Macs used \r
However if you know this you can simply do:
$urls = explode("\n", $_POST['urls']);
EDIT
Actually after testing using regex IS faster than first doing a str_replace() and explode.
Look at http://www.php.net/manual/en/function.preg-split.php and as delimiter use new line sign
or see PHP REGEX - text to array by preg_split at line break
be careful about using just \r or \n because every operating system has "new line" defined another way
see answer by Tgr on SO question PHP REGEX - text to array by preg_split at line break
Use explode
$array=explode("\n",$_POST['textarea']);

Actual input contents are not preseving on most of the browsers [FF,MSIE7/8 and etc]

I'm working on one application ( using PHP, javascript ). Below is the short description about my problem statement
There are two forms avaliable on my application, i.e. SourceFrm and targetFrm.
I am taking input on first form i.e. SourceFrm and doing processing on targetFrm.
Below is the input which I am taking from SourceFrm :
1) Enter your data (Identification of this input box id is 'inputdata' ):
2) Enter id ( Identification input box id is id ):
As per above input feed by user I am posting this data to targetFrm for further processiong.
On TargetFrm :
I am simply assigning inputdata value to php varible.
The spaces which are in between of words are getting lost ( more than one spaces converting to one space).
e.g.
User has added below data on input box and submitted
inputdata:
This is my test.
Here observed that user has added 5 spaces in between 'my' and 'test' word.
After assigning this input data to php variable. After that I printed this value
Below content I am getting
Output:
This is my test.
More than one spaces is converting to one space. This behaviour I checked on all browsers like FF,MSIE7/8 opera, safari, chrome.
If have used '<pre>' before printing php variable i.e.:
print "<pre>";
print $inputdata;
At time spaces are not getting lost (I am getting exact content).
Here my conflict is how do I presrve exact contents without using '<pre>'.
I have used encoding/decoding (htmlentitiesencode() and decode () )functionality, in my further data processing, so it may create some conflict if i replace spaces with . ( May conflict ll occur if i use instead space ).
Is anyone has any ideas, suggestions please suggest.
-Thanks
When you output your variables to HTML, they are parsed as HTML. Any additional white space is brought down to one space.
A simple fix would to replace all spaces with the html entitity to force browsers to display each space.
I wouldn't store the string with all the &nbps; in the database, but when you show it the would ensure that each space is seen.
EDIT
I mean only replace spaces on render...like:
print str_replace(' ', ' ', $inputdata);
HTML is capable of showing only one space. I'm not really sure why, but if you check your source code of rendered webpage containing your string, you'll see that it contains all the space, the browser just doesn't show it.
The same is for other space characters, as tabs.
The way to deal with it depends on type of your content. You can either replace spaces with or leave it as it is or do something completely different, i.e. strip more than one space down to one space.
It really depends on naturel of your data–the only real situation, when you would need more spaces than one, that comes to my mind is if you're trying to indent things with spaces, what actually isn't that great idea.
Edit: older resource:
http://www.sightspecific.com/~mosh/WWW_FAQ/nbsp.html

Categories