phpregexreplacecpu-word

Add a symbol after every word in a string


Given a string, I want an array of strings containing words, each preceded by any non-word characters.

Example input string:

one "two" (three) -four-

The words in the string may be anything, even gibberish, with any amount of punctuation or symbols.

What I would like to see:

array:
one
 "two
" (three
) -four
-

Essentially, for each match the last thing is a word, preceded by anything left over from the previous match.

I will be using this in PHP. I have tried various combinations of preg_match_all() and preg_split(), with patterns containing many variations of "\w", "\b", "[^\w]" and so on.

The Bigger Picture

How can I place a * after each word in the string for searching purposes?


Solution

  • If you just want to add an asterisk after each "word" you could do this:

    <?php
    $test = 'one "two" (three) -four-';
    
    echo preg_replace('/(\w+)/', "$1*", $test);
    ?>
    

    http://phpfiddle.org/main/code/8nr-bpb