puks1978
puks1978

Reputation: 3697

PHP add character to the end of every new word

I have a string of words separated by spaces (except the last word) and I would like to know if there is a way to add a character to the end of each new word. For example:

$string = "this is a short string of words"

would become

$string = "this; is; a; short; string; of; words;"

Thanks

Upvotes: 1

Views: 1609

Answers (3)

hek2mgl
hek2mgl

Reputation: 158050

You can use preg_replace() like this:

$string = "this is a short string of words";
echo preg_replace('~(\w+)~', '$1;',$string);

// output: this; is; a; short; string; of; words;

Upvotes: 1

Chibueze Opata
Chibueze Opata

Reputation: 10054

Explode and Implode:

implode("; ", explode(" ", $string)).";"; 

Upvotes: 3

pirs
pirs

Reputation: 2463

$str = 'lorem ipsum';  
$str_modified = str_replace(' ','; ',trim($str)).';';

Upvotes: 3

Related Questions