Dan Dan - 1 month ago 19
PHP Question

preg_match_all between dynamic tags

I would like to grab each of my virtual hosts configurations and put them in an array using preg_match_all so I can extract information from each of them, for example...

$vHostConfig = ' <VirtualHost *:80>
ServerName localhost
DocumentRoot c:/wamp/www
<Directory "c:/wamp/www/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
<VirtualHost *:8080>
ServerName testing.com
DocumentRoot c:/wamp/www/testing.com
<Directory "c:/wamp/www/testing.com">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
<VirtualHost 127.0.0.1:80>
ServerName testing2.com
DocumentRoot c:/wamp/www/testing2.com
<Directory "c:/wamp/www/testing2.com">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
# <VirtualHost *:80>
# ServerName testing3.com
# DocumentRoot c:/wamp/www/testing3.com
# <Directory "c:/wamp/www/testing3.com">
# Options +Indexes +Includes +FollowSymLinks +MultiViews
# AllowOverride All
# Require local
# </Directory>
# </VirtualHost>';

preg_match_all(<<what to put here>>, $vHostConfig, $vHostConfigMatches);


I would like to grab only the active configurations without a # at the beginning of the line meaning I should have three strings starting with
<VirtualHost
and finishing with
</VirtualHost>
in $vHostConfigMatches array. Is this possible?

Answer

You could use this regular expression:

preg_match_all('/^\h*<VirtualHost.*?>.*?\R\h*<\/VirtualHost>/sm',
               $vHostConfig, $vHostConfigMatches);  

Note that the array $vHostConfigMatches will have an additional nesting level, so just take the first one with reset:

print_r(reset($vHostConfigMatches));
Comments