Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string if next chracter is specific character e.g 'abc'

Tags:

regex

php

I currently have a string shown below,

$string = "4WL533cba00780352524MT_FAILED(SCRNotInAllowList)                  STATUS_NOT_AVAILABLE";

I followed online tutorial shows:

(gif|jpg)   Matches either "gif" or "jpeg".

From my case i only need to split when the text contain DN_ or MT_

$data = preg_split("/[\s,(DN_|MT_),]+/", trim($string));

output

[0] => Array
    (
        [0] => 4WL533cba00780352524
        [1] => FAILE
        [2] => SCR
        [3] => otInAllowList
        [4] => S
        [5] => A
        [6] => US
        [7] => O
        [8] => AVAILABLE
    )

however I expect the output to be:

[0] => Array
    (
        [0] => 4WL533cba00780352524
        [1] => MT_FAILED(SCRNotInAllowList)
        [2] => STATUS_NOT_AVAILABLE
    )

Hope you guys can help me out.

like image 779
maikucao Avatar asked Feb 13 '23 00:02

maikucao


2 Answers

In your regex pattern you wrap the intended pattern in a character class and fail to use the alternation operator - you might wish to have a look at this regex site for detailed explanations of basic syntax of regular expressions, the background theory and extension features in common regex engines.

In your code use

$data = preg_split("/\s+|(?=DN_|MT_)/", trim($string));

Brief explanation of the pattern:

you want to split either at sequences of whitespace or on occurrences of one of the strings 'DN_', 'MT_'. In the latter case you want the match of the split pattern be a part of the next element in the result array. Therefore you enclose the pattern in the positive lookahead operator which provides trailing context for a match. Effectively this matches the empty string if this match is followed by 'DN_' or 'MT_'.

like image 149
collapsar Avatar answered Feb 25 '23 04:02

collapsar


$string = "4WL533cba00780352524MT_FAILED(SCRNotInAllowList)                  STATUS_NOT_AVAILABLE";

$data = preg_split("/\s+|(?=DN_|MT_)/", trim($string));
print_r($data);

output

Array
(
[0] => 4WL533cba00780352524
[1] => MT_FAILED(SCRNotInAllowList)
[2] => STATUS_NOT_AVAILABLE
)
like image 34
mpapec Avatar answered Feb 25 '23 04:02

mpapec