When dealing with variable delimiters, regex is a sensible choice.
I recommend preg_split()
to instantly create a flat array of values. The pattern maintains that words starting with #
may not contain a space and if a word does not start with #
, then it should contain all subsequent words that do not start with #
.
Code: (Demo)
var_export(
preg_split(
'/(?:#\S+|[^# ]+(?: [^# ]+)*)\K /',
'#now my time #Cairo travel #here'
)
);
Output:
array (
0 => '#now',
1 => 'my time',
2 => '#Cairo',
3 => 'travel',
4 => '#here',
)
Breakdown:
#/(?:#\S+|[^# ]+(?: [^# ]+)*)\K /
# ↓↓↓↓ ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ ↓↓↳match literal space
# ↓↓↓↓ ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ ↳↳forget any previously matched characters
# ↓↓↓↓ ↳↳↳↳↳↳↳↳↳↳↳↳↳↳↳↳↳↳↳match non-hashed words separated by space
# ↳↳↳↳match hashed word
For a more in-depth break down of the pattern syntax, try it at regex101.com