PHP clear up Array preg_grep

269 views Asked by At

I have currently a problem with arrays in php, i requested all <li> tags from an html site with:

$dochtml = new DOMDocument();
$dochtml -> loadHTMLFile("my.html");

/*get all li’s*/
$lis = $dochtml -> getElementsByTagName('li');

My Html Body:

<li>gfvgvefg</li>
<li>ferfergegeg</li>
<li id="vdfvdfvf"></li>
<li id="id_1"> My Value 1</li>
<li id="id_2"> My Value 2</li>
<li id="id_3"> My Value 3</li>
<li id="id_4"> My Value 4</li>
<li></li>
<li id="efgvefgvfg">gfegvefgbv</li>

then i echo all id’s and values from my <li> tags:

    foreach($lis as $key) {

        $id = $key -> getAttribute('id');
        $value = $key -> nodeValue;

        echo $id. ' - '.$value.'<br>';

    }

Output:

0 - gfvgvefg
0 - ferfergegeg
vdfvdfvf - 0
id_1 - My Value 1
id_2 - My Value 2
id_3 - My Value 3
id_4 - My Value 4 
0 - 0
efgvefgvfg - gfegvefgbv

You see some id’s are 0, and values too.

What i want is this Output (print_r):

Array ( [id_1] => My Value 1
     [id_2] => My Value 2
     [id_3] => My Value 3
    [id_4] => My Value 4)

So only the id’s with id_* and the correct Value, in an array.

I try this:

foreach($lis as $key) {
    // gets, and outputs the ID and content of each DIV
    $id = $key -> getAttribute('id');
    $value = $key -> nodeValue;

    //echo $id. ' - '.$value.'<br>';


    $array = array($value => $id);
    $matches  = preg_grep('/^id_(\w+)/i', $array);
    print_r($matches);
}

but i get this output (print_r):

Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( )

no id no value, nothing. I know i can use array_keys by preg_grep, but then i get only the id’s and the empty arrays…

Here is the code in an online compile, for better understanding.

Code Online Compiled

Help me please.

2

There are 2 answers

3
u_mulder On BEST ANSWER

Do everything in a single foreach:

$arrLis = array();
foreach($lis as $key) {

    $id = $key -> getAttribute('id');

    // check if `id` starts with `id_` string
    if (strpos($id, 'id_') === 0) {
        $value = $key -> nodeValue;

        echo $id. ' - '.$value.'<br>';

        $arrLis[$id] = $value;
    }
}

print_r($arrLis);
0
Casimir et Hippolyte On

The same using XPath:

$dom =new DOMDocument;
$dom->loadHTMLFile("my.html");
$xp = new DOMXPath($dom);

$nodeList = $xp->query('//li[starts-with(@id, "id_")]');

foreach ($nodeList as $node) {
    $result[$node->getAttribute('id')] = $node->nodeValue;
}

print_r($result);