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
)
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.
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.
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.
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.
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...
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With