I have this code index.php :
$d00m = file_get_contents('named.txt');
foreach ($d00m as $dom) {
preg_match_all('#zone "(.*)"#', $dom, $domsws);
$site = $domsws[0];
}
echo "$site";
The named.txt
file content content is:
zone "site.com" {
zone "site2.com" {
zone "site3.com" {
I need a sorted output in browser :
site1.com
site2.com
site3.com
$domsws
is a 2-dimensional array. The first dimension is for the whole regexp match and each capture group, the second dimension is for each match (you can invert this by using the PREG_SET_ORDER
flag). Since the site names are in capture group 1, they're in $domsws[1]
, which is an array of all these capture group matches. So you should do:
Also, $d00m
is a string, not an array, so you don't need to loop over it.
$d00m = file_get_contents('named.txt');
preg_match_all('#zone "(.*)"#', $d00m, $domsws);
$site = $domsws[1];
print_r($site);
Use file
instead of file_get_contents
. This will give you an array with each line being an item of the array. No messing with explode
.
$d00m = file('named.txt');
Then loop through them and do a preg_replace to store the value into a new array. You can then sort that array using sort
or natsort
. I personally would use the latter.
Here's some code you can play around with:
<?php
// CREATE A NEW ARRAY TO HOLD OUR OUTPUT
$site_list = array();
// IMPORT THE FILE INTO AN ARRAY
$d00m = file('named.txt');
// LOOP THROUGH THE ARRAY AND STORE THE SITE NAME INTO THE ARRAY
foreach ($d00m as $dom) {
$site_list[] = preg_replace('~zone "(.*?)" \{~', '$1', $dom);
}
// DO A NATURAL SORT OF THE NUMBERS
natsort($site_list);
// DUMP OUT THE DATA
print_r($site_list);
Using preg_replace
provides a way to keep the part you want $1
and throw away everything else. $1
contains whatever was captured inside the parenthesis. (.*?)
means to grab any character .
, any number of times *
until you hit the next part of the expression ?
. In this case, it will stop once it gets to the closing quotation mark.
Here's an example for you.
With a named.txt
file like this:
zone "site.com" {
zone "site2.com" {
zone "site3.com" {
zone "site16.com" {
zone "site4.com" {
zone "site77.com" {
zone "site34.com" {
zone "site5.com" {
zone "site999.com" {
zone "site34.com" {
zone "site11.com" {
zone "site8.com" {
zone "site64.com" {
You'd get a result like this:
Array
(
[0] => site.com
[1] => site2.com
[2] => site3.com
[4] => site4.com
[7] => site5.com
[11] => site8.com
[10] => site11.com
[3] => site16.com
[9] => site34.com
[6] => site34.com
[12] => site64.com
[5] => site77.com
[8] => site999.com
)