Reputation: 37464
I have this string in $s
:
ben say (#yellow) hey
At the moment I'm using:
$parts = array_filter(preg_split('/\s+/', $s));
So i have an output of array elements:
[0] ben
[1] say
[2] (#yellow)
[3] hey
Would it be possible to create an array structure like this:
[0] ben
[1] say
[2] (
[3] #yellow
[4] )
[5] hey
Upvotes: 3
Views: 342
Reputation: 14492
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",
)
*/
Upvotes: 0
Reputation: 160833
You could split it by Lookahead and Lookbehind Zero-Width Assertions
:
$parts = array_filter(preg_split('/\s+|(?=[()])|(?<=[()])/', $s));
Upvotes: 3
Reputation: 43619
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.
Upvotes: 1
Reputation: 2493
<?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
Upvotes: 0
Reputation: 3245
this will work:
$parts = array_filter(preg_split('/[\s\(\)]+/', $s));
Upvotes: -2