user3436467
user3436467

Reputation: 1775

PHP regex to include additional criteria

I have a php regex which works but I would like to modify it to include one more condition

preg_match_all('/-----BEGIN CERTIFICATE REQUEST-----[^-]*-----END CERTIFICATE REQUEST-----/s', $file, $matches);

I am loading a file as a string which contains the following blocks of text

-----BEGIN CERTIFICATE REQUEST-----
MIIEezCCA2MCAQAwcjELMAkGA1UEBhMCVVMxDTALBgNVBAgMBFV0YWgxDTALBgNV
ObtIDOoce4eY4Z76AbLUDVuiIZEDI95Rlt6Ha5/DVJZtoljkVQ42RrmP/Yu26Xk=
-----END CERTIFICATE REQUEST-----

-----BEGIN NEW CERTIFICATE REQUEST-----
AHAAdABvAGcAcgBhAHAAaABpAGMAIABQAHIAbwB2AGkAZABlAHIDAQAwgc8GCSqG
SIb3DQEJDjGBwTCBvjAOBgNVHQ8BAf8EBAMCBPAwEwYDVR0lBAwwCgYIKwYBBQUH
-----END NEW CERTIFICATE REQUEST-----

Currently the above regex catches the first block but not the second block, how can I improve the regex to catch both? The second block has an extra word NEW in the header and footer. Ideally i would like a single regex to be flexible and catch either or.

Upvotes: 0

Views: 34

Answers (1)

JvdV
JvdV

Reputation: 75890

As per my earlier comment, maybe try either:

-----BEGIN (?:NEW )?CERTIFICATE REQUEST-----[^-]*-----END (?:NEW )?CERTIFICATE REQUEST-----

Or:

-{5}BEGIN ((?:NEW )?CERTIFICATE REQUEST-{5})[^-]*-{5}END \1

See how this handles your string here. Key to what it is you are after is in both cases to include (?:NEW )? to optionally include the literal word "NEW". In my second pattern I simply caught this option including the repetitional text into a capture group which I used in a later reference.

Upvotes: 1

Related Questions