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.
My Answer:
You can modify the regex pattern to make the word "NEW" optional by using a question mark after it. Here's the updated regex pattern:
php
preg_match_all('/-----BEGIN(?: NEW)? CERTIFICATE REQUEST-----[^-]*-----END(?: NEW)? CERTIFICATE REQUEST-----/s', $file, $matches);
This pattern will match both blocks of text, regardless of whether they contain the word "NEW" or not.
Rate this post
5 of 5 based on 3957 votesComments