Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regular expression to match words

Tags:

regex

php

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?

like image 651
Testic Avatar asked Feb 18 '13 17:02

Testic


1 Answers

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

like image 176
LeonardChallis Avatar answered Oct 02 '22 01:10

LeonardChallis