Separate textarea value per line in PHP after submitting HTML form

Suppose you have an HTML form and the form contains a textarea. Now you want to get each line of the textarea content and process them separately in PHP for some purpose. So you have to split the textarea value in PHP.

So how can you do that? Continue reading to know…

Here I am going to give you the solution. I am going to show how to separate textarea value per line in PHP after submitting HTML form.

First of all, let’s create our HTML form:



<form method="post">
  <textarea name="domains" rows="12" cols="45"></textarea>
  <br/>
  <input type="submit">
</form>

Now below is our PHP code on the same page:

	<?php
	if (isset($_POST['domains'])) {
		
         $domains = $_POST['domains'];
         $domains_arr=explode( "\n", $domains );
	}
	?>

In the above PHP code, we have taken the textarea value in a variable and then explode the value with “\n”. Every line break has “\n” that we can’t see.

Below is the particular line from above that create an array that contains each line of textarea value:

$domains_arr=explode( "\n", $domains );

Here you can see that we have used the PHP explode() function that can break a string into an array by a delimiter that we specify.

If we print it, we will able to see the array that is something like you can see below:

Array
(
   [0] => https://www.google.com
   [1] => https://www.facebook.com
   [2] => https://twitter.com
)

From the array, you can use the PHP foreach loop to process each data or you can also take a particular line by the index number. Each index of the array represents each line from the textarea after some content inserted and the form submitted.

So we have learned how to separate textarea value per line in PHP. I hope you have understood.

Also, read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *