Frage

I want to replace every anchor on HTML and have use this code but it seems there something missing:

foreach($html->find('div') as $dict) {
    $dict->find('SPAN', 0)->find('A', 0)->href = "link.php?" . $dict->find('SPAN', 0)->find('A', 0)->innertext;
}

The HTML structure is like:

<DIV>
    <SPAN> 
        Text text text <A HREF="link1.php">LINK_A</a>, 
        text text <A HREF="link1.php">LINK_B</a>.
    </SPAN>
</DIV>
...

What I supposed to do with that code is to change all of the anchor on the html become:

<DIV>
    <SPAN> 
        Text text text <A HREF="link.php?LINK_A">LINK_A</a>, 
        text text <A HREF="link.php?LINK_B">LINK_B</a>.
    </SPAN>
</DIV>
...

But the code only works for the first anchor on each span, like:

<DIV>
    <SPAN> 
        Text text text <A HREF="link.php?LINK_A">LINK_A</a>, 
        text text <A HREF="link1.php">LINK_B</a>.
    </SPAN>
</DIV>
...

I tried to modify the code become:

foreach($html->find('div') as $dict) {
    foreach($dict->find('SPAN', 0)->find('A', 0) as $anchor) {
        $anchor->href = "link.php?" . $anchor->innertext;
    }
}

But it get worst. How can I do that? Thanks.

War es hilfreich?

Lösung

You are declaring that you want to find the 1st span only here...

$dict->find('SPAN', 0)
// The 0 means the first one only I expect

Andere Tipps

You are only looping through each div, not each anchor tag you find. Your JavaScript code looks pretty inefficient as well. I'm not familiar with the method you're using, but in jquery you could do something like

$("dic span a").each(function){
    //do something here
    //refer to the anchor tag using $(this)
})
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top