简体   繁体   中英

PHP Regular Expression preg_grep

I have an array that looks something like this:

$array[] = 'MT0001ENG Apricot, dried';
$array[] = 'MT0001SYS Prunus armeniaca L.';
$array[] = 'MT0001YLD 0';
$array[] = 'MT0001MGR 06';
$array[] = 'MT0001SGR 20';
$array[] = 'MT0001NCF 6.25';
$array[] = 'MT0001FCF 0.800';
$array[] = 'MT0001000 1159                          00050';
$array[] = 'MT0001001 2.9         2.6   3.5   4     05165';
$array[] = 'MT0001002 0.1         0.1   0.1   4     00050';
$array[] = 'MT0003ENG Pineapple, raw';
$array[] = 'MT0003SYS Ananas comosus (L.) Merr.';
$array[] = 'MT0003YLD 47';
$array[] = 'MT0003MGR 06';
$array[] = 'MT0003SGR 40';
$array[] = 'MT0003NCF 6.25';
$array[] = 'MT0003FCF 0.800';
$array[] = 'MT0003000 232                           00050';
$array[] = 'MT0003001 0.5         0.5   0.6   4     05165';
$array[] = 'MT0003002 0.1         0.1   0.1   4     00050';

I am putting all the lines, that contains the names, into an array called $names like this:

$names = preg_grep("/ENG/", $array);

But now i want to put all the lines, that contains the protein info, into an array called $protein. Example of protein lines is:

$array[] = 'MT0001001 2.9         2.6   3.5   4     05165';
$array[] = 'MT0003001 0.5         0.5   0.6   4     05165';

As u can see, there is a pattern. All the lines start with MT. Followed by a 4 digit product number. Followed by 3 characters, and for proteins, those are 001:)

I have tried the following, with no luck!

$proteins = preg_grep("/MT{4}[0-9]001/", $array);
$names = preg_grep("/MT\d{4}001.*/", $array);

Match 'MT' followed by 4 digits followed by '001' followed by zero or more of any characters

You can play with this a little easier using a tool like RegExr, heres a link with your example: http://regexr.com?30irf

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