i'm looking for a way to split a string in several words, based on some delimiters.
For example the string word1&word2 !word3 word4 &word5
should give me an array with the following words:
word1
&word2
!word3
word4
&word5
How to reach that? I tried several solution with str_replace() but i cannot figure out the best way to obtain what i need. Maybe the solution could be using regular expressions, but i do not know how to use them.
Try this:
First change any occurence of a group consisting of a single character of class
[&!]
that is preceded by a 'word'-character into' $1'
(=itself, preceded with a blank) and thenexplode()
the string using the blanks as separators.If you need to deal with multiple blanks as separators between the words you could of course replace the (faster)
explode(' ',...)
with a slighty more "refined"preg_split('/ +/',...)
.