Reputation: 18751
I have strings like this:
wh4tever_(h4r4ct3rs +syMb0|s! ASC
wh4tever_(h4r4ct3rs +syMb0|s! DESC
I don't know what the first characters are, but I know that they end by ' ASC'
or ' DESC'
, and I want to split them so that I get an array like:
array(
[0] => 'wh4tever_(h4r4ct3rs +syMb0|s!'
[1] => 'ASC' //or 'DESC'
)
I know it must be absolutely easy using preg_split()
, but regexps are something I assumed I'll never get on well with...
Upvotes: 0
Views: 80
Reputation: 177
Try This,
$str = "wh4tever_(h4r4ct3rs +syMb0|s! ASC";
$str1 = "wh4tever_(h4r4ct3rs +syMb0|s! ASC";
$ar = preg_split('/(ASC|DESC)/i', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$ar1 = preg_split('/(ASC|DESC)/i', $str1, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($ar);
print_r($ar1);
output : Array ( [0] => wh4tever_(h4r4ct3rs +syMb0|s! [1] => ASC ) Array ( [0] => wh4tever_(h4r4ct3rs +syMb0|s! [1] => DESC )
Upvotes: 3
Reputation: 76646
You can use the following regular expression with preg_split()
:
\s(?=(ASC|DESC))
Explanation:
\s
- match any whitespace character(?=
- start of positive lookahead
(ASC|DESC)
- ASC
or DESC
)
- end of positive lookaheadVisualization:
Complete:
$str = 'wh4tever_(h4r4ct3rs +syMb0|s! ASC';
$arr = preg_split('/\s(?=(ASC|DESC))/', $str);
print_r($arr);
Output:
Array
(
[0] => wh4tever_(h4r4ct3rs +syMb0|s!
[1] => ASC
)
Upvotes: 3
Reputation: 59292
You can use this regex:
\s(?=(A|DE)SC)
and split it.
As sshashank124, pointed, it is an extremely good tool which is language agnostic.
Upvotes: 2