Jens
Jens

Reputation: 25

splitting a string with some kind of whitespace

I've got the following code:

$output2 = 'text

more text

ja';
$explode = explode('

', $output);

This works fine and the $explode array prints the following:

Array
(
    [0] => text
    [1] => meer text
    [2] => ja
)

However, the following code doesn't work and I don't know how to fix it:

$output = 'text



more text



ja';

$explode = explode('

', $output);

The $explode array prints the following:

Array
(
    [0] => text
    

    
  //more text
    

    
ja
)

This might seem like a weird question. But the first example is a test I made manually. But the second example is what is actually returned from the database.

Upvotes: 2

Views: 57

Answers (5)

Sebastian Brosch
Sebastian Brosch

Reputation: 43564

You can use preg_split to split your string:

<?php
$output = 'text
&NewLine;
&NewLine;more text
&NewLine;
&NewLine;ja';

$explode = preg_split('/(&NewLine;|(\r\n|\r|\n))+/', $output, -1, PREG_SPLIT_NO_EMPTY);

demo: https://ideone.com/KU0v9t (ideone) or https://eval.in/887393 (eval.in)


The following solution to split on double &NewLine;:

$output = 'text
&NewLine;
&NewLine;more text
&NewLine;
&NewLine;ja
&NewLine;nein';

$explode = preg_split('/(\r\n|\r|\n)*(&NewLine;(\r\n|\r|\n)*){2}/', $output, -1, PREG_SPLIT_NO_EMPTY);

demo: https://ideone.com/0txh5O

Upvotes: 1

Isidro.rn
Isidro.rn

Reputation: 314

As User2486 says, the problem is that there are some hidden characters you are not watching like \n and \r

In your first example you have

'text&NewLine;&NewLine;more text&NewLine;&NewLine;ja'

and in the second

'text\r\n&NewLine;\r\n&NewLine;more text\r\n&NewLine;\r\n&NewLine;ja'

Upvotes: 0

Paun Narcis Iulian
Paun Narcis Iulian

Reputation: 799

normalize your string by removing all new line like chars:

$output = trim(preg_replace('/\s+/', '',$output));

then explode it.

Upvotes: 0

Alex Kapustin
Alex Kapustin

Reputation: 2439

$explode = preg_split('/&NewLine;\s*&NewLine;/', $output);

Upvotes: 0

Niklesh Raut
Niklesh Raut

Reputation: 34914

Adding one line in your code $output =str_replace("\r\n","",$output ); to combine all string in one line so that it would like your first example.

$output =str_replace("\r\n","",$output );
$explode = explode('&NewLine;&NewLine;', $output);
print_r($explode);

Live demo : https://eval.in/887371

Upvotes: 0

Related Questions