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
Post a Comment