Skip to content
Advertisement

PHP: Exploding string => last element is empty, but not recognized as empty

I’m struggling with a behaviour in PHP and finally needed to sign up on stackoverflow as I could not find any answer to my problem for the very first time! 😀

In my code, I’m getting the following content from a textarea (multiple lines):

JavaScript

I’m first exploding the several lines with explode("n", $string);. Second, I explode the elements of each line: explode(";", $string[0]);

The content of key 6 is empty, but PHP only recognizes the last element of the last line as empty:

Exploding the lines with

JavaScript

Exploding first line with

JavaScript

Is last element of first line empty?

JavaScript

No.

Exploding second line with

JavaScript

Is last element of second line empty?

JavaScript

No.

Exploding third line with

JavaScript

Is last element of third line empty?

JavaScript

Yes

Can anyone tell me, why PHP always says that only the last element of the last line is empty, although every last element is?

Thank you very much in advance!

Advertisement

Answer

The browser is normalising the line separation with carriage return line feeds. So when you split on a line feed, you still have a carriage return in the last part.

JavaScript

Output (without the form code upon form submission):

JavaScript

Swap the explode line for the preg_split one above and the output is:

JavaScript

R escape sequence matches any Unicode newline sequence. (Please correct this definition if wrong.)

Note trailing space could be an issue. Be careful with user input.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement