pragmus
pragmus

Reputation: 4043

Split string in php with new line

I've a problem with string spliting.

<?php
    $blackShopArray = preg_split("~[|!,\s\n\b]+~", $cfg['options']['bslist']);
    $blackShopColumn = '';
    foreach($blackShopArray as $shop){
        $blackShopColumn .= $shop . "<br/>";
    }
    echo $blackShopColumn;
?>

This code can't split string by a newline symbol. How to fix it?

Upvotes: 0

Views: 358

Answers (1)

Maytham Fahmi
Maytham Fahmi

Reputation: 33387

\n (newline) and \r (return) control characters are the same as
&#10 and &#13 ASCII control characters in HTML which is
CR (Carriage return) and LF (Line feeed).

But when we want check those out in Regex (regular expression) then they are different. In this case to match those in preg_split.

Therefore we could replace &#10 and &#13 with empty string and use str_split in stead. I am pretty sure it can be done different ways.

Here is my approach:

<?php
$cfg = "Some text will &#13;&#10;go in new line";

$cfg = str_replace("&#10;", "", $cfg);
$cfg = str_replace("&#13;", "", $cfg);
$blackShopArray = str_split($cfg);
$blackShopColumn = '';
foreach ($blackShopArray as $shop)
{
    $blackShopColumn .= $shop . "<br/>";
}
echo $blackShopColumn;
?>

Some references:

Upvotes: 2

Related Questions