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

3k Views Asked by At

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.

4

There are 4 best solutions below

0
On BEST ANSWER

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) . '* ';
0
On

Try this

<?php

$str = 'test test test test test';  
$str = implode("* ", explode(" ", $str))."* ";

echo $str;
0
On

Try other answers or you can also use preg_replace. But not recommended. Avoid using regex when there is some clean alternatives available.

<?php
  $query  = preg_replace( "/[\s]+/", "* ", $query )."*";
  echo $query;
?>

Using array_map

<?php
  $query  = explode( " ", "test test test test test" );
  $query  = array_map( function( $val ) {
    return trim( $val )."* ";
  }, $query );
  $query  = implode( "", $query );
  echo $query;
?>
0
On

Most directly, use preg_replace() to insert an * after each word.

\w+ will match one or more alphanumeric or underscore characters.
\K tells the function to restart the full string match -- so that no characters are removed during replacement.

Code: (Demo)

$string = 'test test test test';

echo preg_replace("/\w+\K/", '*', $string);
// output: test* test* test* test*

For multibyte characters such as cyrillic, add the u pattern modifier.

Code: (Demo)

$string = 'слово слово слово слово';

echo preg_replace("/\w+\K/u", '*', $string);
// output: слово* слово* слово* слово*