How to parse data from textarea by line break and concatenate - php

I want to parse the value from a textarea based on linebreaks and have it converted into one string replacing a line break with a concat character like ;
Basically I want something like:
Hello World
My Name is Carl
I like apples
To:
"Hello World;My name is Carl;I like apples"
I'm wanting to submit it to a text column in a database and then when I retrieve the data later for viewing I want it to parse back to line-breaks using the ; as the identifier character. I'm using CodeIgniter so if there are any helper functions I can use that would be neat.

As per your requirement, you dont want to add ";" or anything. You want to show what your getting. Then use nl2br
$text = nl2br($this->input->post("textarea_name"));
store it in db and display directly without additional code.

Related

PHP/CSV : how to echo an end of row?

I manually echo some data in a .csv file. For each row, I use the following code :
...(some data)."\n";
Now, I want to use a form where the user can input the end of row. For instance, if he wants his rows to be ended by "\n", he types : \n in the form.
My problem is how to handle this value in the PHP echo code ?
I've tried .$var, ."$var", I also tried to escape the double quotes, but I can't manage to reach my goal.
Thanks
You could instead make them type a character that they wouldn't use as content, for example | might work.
Then all you'd have to do is replace | by \n inside the string, you can do it this way:
$content = str_replace ('|','\n', $content);

Php Split text from html text area

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>";

How to fetch and output properly data from table, inserted with mysqli_real_escape_string

I used mysqli_real_escape_string() to insert the data from a html form textarea input into the MySQL table.
The input was like:
It was inserted in table properly.
But when I fetch it and try to echo it, it prints in single line as
Hi H"ow" are you? I 'm f'ine /\ How you doing?
How to display it the way it was inserted?
use nl2br() to convert new lines to <br> then store it.
for more information : http://php.net/manual/en/function.nl2br.php
for whitespaces and indentation use html_entities()
If it also doesnt work then you would have to do it using str_replace() by replacing those charcter with one in html like

Feeding multi-line string value to jquery methods

How do I feed string variable holding multiline value in it to jquery method like prepend? I need it to construct a form pass by drupal search module like - $('#divsearch').prepend('<?php print $search_box; ?>'). Thanks a bunch.
Use json_encode() to encode the string, like this:
$('#divsearch').prepend('<?php print json_encode($search_box); ?>');
This will encode newlines as \n instead of literally rendering them...giving you your current syntax errors.
I think the problem is that you can have carriage returns or new lines in you string lets take out the php and show what i mean
$('#divsearch').prepend('<div />');
this would work
$('#divsearch').prepend('<div>some text that goes
in a div</div>');
this does not work
$('#divsearch').prepend('<div>some text that goes'+
'in a div</div>');
this woould

PHP "spinning" content via random find/replace

I'm using file_get_contents('mysourcefile.html') to load the contents of mysourcefile.html into mysql db.
I have two things that I want to do to the contents of mysourcefile.html before I insert it into the db.
First...
I'd like to do a find/replace on specific string matches contained in mysourcefile.
For example: the tags that a user may place in their source input files would look something like this:
Welcome to [site-name], located at
[site-url] contact us at [site-email]
if you need help.
And I'd like to do a simple string match replacement on these values as they appear in the source file before they are written to the db. The replacement text would come from the wordpress database setup fields. For example, get_option('admin_email') and get_option('home')
Secondly...
I'd also like to allow the user to specify, via a special bracket, a string of words in which to use in order to randomize the content each time its imported, using the same input source file.
For example, in the above sentence, it might be encoded in the source file like so:
I'd also [%like|prefer|want%] to
[%allow|permit%]the user to
[%specify|declare|select%] via a
[%special|unique|predefined%] bracket,
a string of [%words|characters|text%]
in which to use in order to randomize
the content from site to site, using
the same input source file.
So I want to parse that content string and do a simple random replacement of each set element to pick one word out of the collection and use that word for the insert.
Its basically a crude content replacement/spinner and I'm looking for some direction and methods which I could use to do it.
For the first part:
$tags = array('[site-name]', '[site-url'], '[site-email]');
$words = array("My Name", "My URL", "My Email");
$content = str_replace($tags, $words, $content);
The second part might be a little trickier. But the process is:
Grab the content between "[%" and "%]" tags.
implode("|", $string);
Pick a random value
So .. you'll need someone who knows Regex.

Categories