Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode by comma and new line together [duplicate]

I have a basic textarea. When user enter some text I explode words by comma ",". Now I also want to seperate words by new line. How can I do it.

This is my code part that explodes words by comma.

if(isset($_POST["btn"])){
    $words     = $_POST["inp_text"];
    $words_arr = explode(",",$words);

    foreach($words_arr as $word){
        echo $word."<br>";
    }
}

How can I add new line functionality to this code part. I think, I should generate a string from $word in loop than after loop I should explode this string by new line again.

Is there a better idea?

For better understading I add some examples.

input:

apple, melon, a, b, c

output:

apple melon a b c

input (with new line)

x,y,z,a
b
c

output:

x y z a b c
like image 635
hakki Avatar asked Oct 26 '25 04:10

hakki


2 Answers

Try with this:

$split_strings = preg_split('/[\ \n\,]+/', $your_string);
like image 71
Ahmed Ziani Avatar answered Oct 27 '25 19:10

Ahmed Ziani


You can use preg_split in order to split your string into words, no matter is there is a comma or a new line.

$wordsArray = preg_split('/\W/', $yourString, 0, PREG_SPLIT_NO_EMPTY);
like image 21
Vic Abreu Avatar answered Oct 27 '25 19:10

Vic Abreu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!