2

I am trying to clear a string of " " , , , . , ? , ! but the result array contains an empty element.

My code:

$mesaj = "Ana are mere, dar nu are si nuci? Matei are nuci!";
$keywords = preg_split("/[\s,.?!]+/", $mesaj);
print_r($keywords);

The output is as follows:

Array (
    [0] => Ana
    [1] => are
    [2] => mere
    [3] => dar
    [4] => nu 
    [5] => are
    [6] => si
    [7] => nuci
    [8] => Matei
    [9] => are
    [10] => nuci
    [11] => 
)

I want to remove the empty elements from the above array. How can this be done?

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Filip
  • 147
  • 9

1 Answers1

4

Use PREG_SPLIT_NO_EMPTY flag:

$keywords = preg_split("/[\s,.?!]+/", $mesaj, -1, PREG_SPLIT_NO_EMPTY);

The -1 in the above statement is to enable the use of flags. See the documentation for preg_split() for more information.

Online demo

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • But it does not work:( It echoes this: Array ( [0] => Ana are mere, dar nu are si nuci? Matei are nuci! ) – Filip Feb 23 '14 at 12:07
  • @Filip: Are you sure you're seeing the latest version of the answer? I've updated the answer to include a working demo. – Amal Murali Feb 23 '14 at 12:08