Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explode a multi-line string?

Tags:

php

explode

I have a string that has different values on each line:

$matches="value1
value2
value3
value4
value5
";

I want to explode the whole string in to an array consisting of the values separeted. I know how to explode a space separated string, like explode(' ', $matches). But how do i use the explode function on this type of string?

I tried this:

$matches=explode('\n',$matches);
print_r($matches);

But the result is like:

Array
(
    [0] => hello
hello
hello
hello
hello
hello
hello

)
like image 276
Sujit Agarwal Avatar asked May 28 '11 16:05

Sujit Agarwal


People also ask

How do you break a string with multiple lines?

You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python. You can use it to join text on separate lines and create a multiline string.

How do you break a text line in Python?

Python String splitlines() method is used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break(optional). Parameters: keepends (optional): When set to True line breaks are included in the resulting list.

Can a string hold multiple lines?

There are three ways to create strings that span multiple lines: By using template literals. By using the + operator – the JavaScript concatenation operator. By using the \ operator – the JavaScript backslash operator and escape character.

What does exploding a string do?

PHP | explode() Function The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.


2 Answers

You need to change '\n' to "\n".

From PHP.net:

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

\n linefeed (LF or 0x0A (10) in ASCII)
More...

like image 51
Tim Cooper Avatar answered Sep 19 '22 11:09

Tim Cooper


Read manual

Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

So use "\n" instead of '\n'

Also, instead of \n you can use PHP_EOL constant.
In the Windows "\r\n" can be used as end of line, for this case you can make double replacement:
$matches=explode("\n", str_replace("\r","\n",$matches));

like image 27
OZ_ Avatar answered Sep 18 '22 11:09

OZ_