Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explode a string, with spaces and new lines?

Tags:

php

delimiter

I would like to explode a string (separated based on a delimiter and placed into an array), using both a space (" ") and a newline ("\n") as a delimiter.

The method (which I don't think is the best way) is to:

  1. Explode the array by spaces
  2. Remake the string from the array
  3. Explode it again for new lines
  4. MySQL escape the individual elements.

Question: How do I exploded a string by both a space and new line?

Reference to: new line Array

like image 953
tread Avatar asked Jul 29 '13 07:07

tread


People also ask

How to split a string with newline?

Split String at Newline Split a string at a newline character. When the literal \n represents a newline character, convert it to an actual newline using the compose function. Then use splitlines to split the string at the newline character. Create a string in which two lines of text are separated by \n .

How do you put a space in a split string?

To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do you split a new line in JavaScript?

Splitting a String on the Newline Character The character to represent a new line in JavaScript is the same as in other languages: \n .


1 Answers

You could just do a

$segments = preg_split('/[\s]+/', $string);

This function will split $string at every whitespace (\s) occurrence, including spaces, tabs and newlines. Multiple sequential white spaces will count as one (e.g. "hello, \n\t \n\nworld!" will be split in hello, and world! only, without empty strings in the middle.

See function reference here.

like image 151
Paolo Stefan Avatar answered Nov 02 '22 08:11

Paolo Stefan