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?

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

But it does not work:( It echoes this: Array ( [0] => Ana are mere, dar nu are si nuci? Matei are nuci! )
@Filip: Are you sure you're seeing the latest version of the answer? I've updated the answer to include a working demo.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.