简体   繁体   中英

Split String With preg_match

I have string :

$productList="
Saluran Dua(Bothway)-(TAN007);
Speedy Password-(INET PASS);
Memo-(T-Memo);
7-pib r-10/10-(AM);
FBI (R/N/M)-(Rr/R(A));
";

i want the result like this:

Array(
[0]=>TAN007
[1]=>INET PASS
[2]=>T-Memo
[3]=>AM
[4]=>Rr/R(A)
);

I used :

$separator = '/\-\(([A-z ]*)\)/';
preg_match_all($separator, $productList, $match);
$value=$match[1];

but the result:

Array(
[0]=>INET PASS
[1]=>AM
);

there's must wrong code, anybody can help this?

Your regex does not include all the characters that can appear in the piece of text you want to capture.

The correct regex is:

$match = array();
preg_match_all('/-\((.*)\);/', $productList, $match);

Explanation (from the inside to outside):

  • .* matches anything;
  • (.*) is the expression above put into parenthesis to capture the match in $match[1] ;
  • -\\((.*)\\); is the above in the context: it matches if it is preceded by -( and followed by ); ; the parenthesis are escaped to use their literal values and not their special regex interpretation;
  • there is no need to escape - in regex; it has special interpretation only when it is used inside character ranges ( [AZ] , fe) but even there, if the dash character ( - ) is right after the [ or right before the ] then it has no special meaning; eg [-AZ] means: dash ( - ) or any capital letter ( A to Z ).

Now, print_r($match[1]); looks like this:

Array
(
    [0] => TAN007
    [1] => INET PASS
    [2] => T-Memo
    [3] => AM
    [4] => Rr/R(A)
)

试试这个ReGex

$separator = '#\-\(([A-Za-z0-9/\-\(\) ]*)\)#';

for the 1th line you need 0-9

for the 3th line you need a - in and

in the last line you need () try this

 #\-\(([a-zA-Z/0-9(\)\- ]*)\)#

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