php - How to split string on multiple delimiters keeping some delimiters? -


i'm looking way split string in several words, based on delimiters.

for example string word1&word2 !word3 word4 &word5 should give me array following words:

word1 &word2 !word3 word4 &word5 

how reach that? tried several solution str_replace() cannot figure out best way obtain need. maybe solution using regular expressions, not know how use them.

try this:

$src='word1&word2 !word3 word4 &word5'; $arr=explode(' ',$src=preg_replace('/(?<=[\w])([&!])/',' $1',$src)); echo join('<br>',$arr); // present result ... 

first change occurence of group consisting of single character of class [&!] preceded 'word'-character ' $1' (=itself, preceded blank) , explode()the string using blanks separators.

if need deal multiple blanks separators between words of course replace (faster) explode(' ',...) slighty more "refined" preg_split('/ +/',...).


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -