简体   繁体   中英

regex pattern needed for extracting multiple parts of a specific string in php

I have a string like this in my PHP code:

$string = "(A)[B]C/D/E:F?G";

how can i extract A , B , C , D , E , F , G parts from the string with regex?

i want a function, for example some_function_do_some_regex , that take my $string as parameter and extract the seven wanted parts from it

$parts = some_function_do_some_regex($string);
print_r($parts);

// OUTPUT
/*
Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
    [4] => E
    [5] => F
    [6] => G
)
*/

UPDATED:
I had to mention an important thing, but I forgot, I'm sorry. Keep in mind that the seven parts in string (A, B, C, D, E, F, G), are for sample and their value can change,

for example consider this:

$string = "(aaa)[bbb]ccc/ddd/eee:fff?ggg";

the output will be something like this

/*
Array
(
    [0] => aaa
    [1] => bbb
    [2] => ccc
    [3] => ddd
    [4] => eee
    [5] => fff
    [6] => ggg
)
*/

and another important note:
in the parts 1 to 6, there is no symbol character, we have az and 0-9 values, but for the last part (the part after the question mark), we can have any character like [ and / and anything else.

It means that the parts structure are very important.

Here is a description of every part:
Part A : everything between ( and )
Part B : everything between [ and ]
Part C : everything before first / and after ]
Part D : everything between first and second /
Part E : everything after second / and before :
Part F : everything after : and before ?
Part G : everything after ?

As suggested by Rohit, here's the PHP implementation of the pattern..

$string = "(A)[B]C/D/E:F?G";
preg_match_all('/\w/', $string, $matches);
print_r($matches[0]);

Thanks for Rohit Jain help. I create this answer:

<?php

$string = "(a)[b]c/d/e:f?g:part?with(non-alphabetical)[characters]!";
preg_match_all('/([a-zA-Z0-9]+)|\?([^?]*)$/', $string, $sixparts);
preg_match_all('/([a-zA-Z0-9]+)|.*?\?(.*)$/', $string, $sevenpart);

$part_a = $sixparts[0][0];
$part_b = $sixparts[0][1];
$part_c = $sixparts[0][2];
$part_d = $sixparts[0][3];
$part_e = $sixparts[0][4];
$part_f = $sixparts[0][5];
$part_g = $sevenpart[2][0];

echo $part_a; // a
echo $part_b; // b
echo $part_c; // c
echo $part_d; // d
echo $part_e; // e
echo $part_f; // f
echo $part_g; // g:part?with(non-alphabetical)[characters]!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM