Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top