Search code examples
phpimplodemultibyte

Add character after each word in a string (multibyte-safe)


How can I implode character after each word?

I have tried the following:

$query = implode("* ", preg_split("/[\s]+/", $query));

but it always ignores one word. for example: test test will give me test* test, test will give me test, test test test test will give me test* test* test* test

Also tried $query = implode("*", str_split($query)); but it gives me gibberish if query is in Cyrillic characters.


Solution

  • implode will join strings together and insert a "glue string" in between each item.

    If you want to change each and every string, you can use array_map instead.

    implode(array_map(function($item) { return $item . '* '; }, $array));
    

    And I hope you are not doing funky stuff with a database query (considering your variable name). If you want to use variable db queries, use parametrized queries instead.

    Another "hack" is to implode your array and then insert the missing string at the end of the resulting string:

    implode('* ', $array) . '* ';