I have this string in $s
:
ben say (#yellow) hey
At the moment I\'m using:
$parts = array_filter(preg_sp
this will work:
$parts = array_filter(preg_split('/[\s\(\)]+/', $s));
Well you can try this replacement:
$s = str_replace(array('(', ')'), array('( ', ' )'), $s);
$parts = array_filter(preg_split('/\s+/', $s));
The trick here is to add a space between your (
and the word so that it gets splitted. However, it will only work specific to your example. Things like ((
might cause some unwanted results. If so you can try using preg_replace instead.
You could split it by Lookahead and Lookbehind Zero-Width Assertions
:
$parts = array_filter(preg_split('/\s+|(?=[()])|(?<=[()])/', $s));
<?php
// function to explode on multiple delimiters
function multi_explode($pattern, $string, $standardDelimiter = ':')
{
// replace delimiters with standard delimiter, also removing redundant delimiters
$string = preg_replace(array($pattern, "/{$standardDelimiter}+/s"), $standardDelimiter, $string);
// return the results of explode
return explode($standardDelimiter, $string);
}
// test
// set up variables
$string = "zero one | two :three/ four\ five:: six|| seven eight nine\n ten \televen twelve thirteen fourteen fifteen";
$pattern = '/[:\|\\\\\/\s]/'; // colon (:), pipe (escaped '\|'), slashes (escaped '\\\\' and '\/'), white space (\s)
// call function
$result = multi_explode($pattern, $string);
// display results
var_dump($result);
?>
Source : http://php.net/manual/en/function.explode.php Examples
A one liner which will work exactly as wanted (you don't even need array_filter
):
$s = "ben say (ewfs) as";
$parts = preg_split('/\s+|(\()|(\))/', $s, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)
/*
Array(
0 => "ben",
1 => "say",
2 => "(",
3 => "ewfs",
4 => ")",
5 => "as",
)
*/