Domanda

Di 'Ho il seguente link:

<li class="hook">
      <a href="i_have_underscores">I_have_underscores</a>
</li>

Come potrei, rimuovere le sottolineature solo nel testo e non il href? Ho str_replace usato, ma questo rimuove tutti i caratteri di sottolineatura, che non è l'ideale.

Quindi, in pratica mi sarebbe lasciato con questa uscita:

<li class="hook">
      <a href="i_have_underscores">I have underscores</a>
</li>

Qualsiasi aiuto, molto apprezzato

È stato utile?

Soluzione

E 'più sicuro per analizzare HTML con DOMDocument invece di regex. Prova questo codice:

<?php

function replaceInAnchors($html)
{
    $dom = new DOMDocument();
    // loadHtml() needs mb_convert_encoding() to work well with UTF-8 encoding
    $dom->loadHtml(mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"));

    $xpath = new DOMXPath($dom);

    foreach($xpath->query('//text()[(ancestor::a)]') as $node)
    {
        $replaced = str_ireplace('_', ' ', $node->wholeText);
        $newNode  = $dom->createDocumentFragment();
        $newNode->appendXML($replaced);
        $node->parentNode->replaceChild($newNode, $node);
    }

    // get only the body tag with its contents, then trim the body tag itself to get only the original content
    return mb_substr($dom->saveXML($xpath->query('//body')->item(0)), 6, -7, "UTF-8");
}

$html = '<li class="hook">
      <a href="i_have_underscores">I_have_underscores</a>
</li>';
echo replaceInAnchors($html);

Altri suggerimenti

È possibile utilizzare un HTML DOM parser per ottenere il testo all'interno dei tag, e quindi eseguire la funzione str_replace() sul risultato.


Uso della DOM Parser ho linkato, è semplice come qualcosa di simile a questo:

$html = str_get_html(
    '<li class="hook"><a href="i_have_underscores">I_have_underscores</a></li>');
$links = $html->find('a');   // You can use any css style selectors here

foreach($links as $l) {
    $l->innertext = str_replace('_', ' ', $l->innertext)
}

echo $html
//<li class="hook"><a href="i_have_underscores">I have underscores</a></li>

Questo è tutto.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top