3

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
hakki
  • 6,181
  • 6
  • 62
  • 106

4 Answers4

6

Try with this:

$split_strings = preg_split('/[\ \n\,]+/', $your_string);
Ahmed Ziani
  • 1,206
  • 3
  • 14
  • 26
  • This answ\er u\ses unne\cessar\y es\c\a\ping in the character class. (and is a code-only answer hence it is low-value). – mickmackusa Jul 31 '18 at 07:34
3

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);
Vic Abreu
  • 500
  • 4
  • 12
1
<?php
$output = str_replace(array("\n", "\r"), '', $input);
?>

\n is a newline, you replace it with a normal space. Definetly no need for complicated regex here!:)

Xatenev
  • 6,383
  • 3
  • 18
  • 42
  • 1
    but if I do that my array still has not splitted words (elements) by new line. It only deletes \n after words. Am I wrong? – hakki Apr 13 '15 at 13:36
  • Don't get you sorry, this removes ALL new lines in your $input string – Xatenev Apr 13 '15 at 13:38
  • @hakkikonu Oh yeah, sorry, of course u have to give str_replace an array, fixed! (Code was untested) – Xatenev Apr 13 '15 at 13:42
-4

You could split the input by lines, then for each line, split the line by words.

<?php
if(isset($_POST["btn"])){
    $data = $_POST["inp_text"];
    $lines = explode("\n", $data);

    foreach($lines as $line)
    {
        $words = explode(' ', $lines);
        foreach($words as $word)
        {
            echo $word.' ';
        }
    }
}
Mex
  • 1,011
  • 7
  • 16