Pergunta

Eu estou tentando corresponder etiquetas <a> dentro do meu conteúdo e substituir, em seguida, com o texto do link seguido pela url entre colchetes para uma impressão-versão. O exemplo a seguir funciona se houver apenas o "href". Se o <a> contém outro atributo, ele corresponde muito e não retorna o resultado desejado. Como posso combinar com a URL e o texto do link e é isso?

Aqui está o meu código:

<?php
$content = '<a href="http://www.website.com">This is a text link</a>';
$result = preg_replace('/<a href="(http:\/\/[A-Za-z0-9\\.:\/]{1,})">([\\s\\S]*?)<\/a>/',
     '<strong>\\2</strong> [\\1]', $content);
echo $result;
?> 

resultado desejado:

<strong>This is a text link </strong> [http://www.website.com]

Obrigado, Jason

Foi útil?

Solução

Você pode fazer o jogo ungreedy usando ?. Você também deve ter em conta que pode haver atributos antes de o atributo href.

$result = preg_replace('/<a [^>]*?href="(http:\/\/[A-Za-z0-9\\.:\/]+?)">([\\s\\S]*?)<\/a>/',
    '<strong>\\2</strong> [\\1]', $content);

Outras dicas

Você deve estar usando DOM para analisar HTML, não expressões regulares ...

Edit:. Código atualizado para fazer simples análise regex no valor do atributo href

Edit # 2:. Feito o regressiva de loop para que ele possa lidar com várias substituições

$content = '
<p><a href="http://www.website.com">This is a text link</a></p>
<a href="http://sitename.com/#foo">bah</a>

<a href="#foo">I wont change</a>

';


 $dom = new DOMDocument();
    $dom->loadHTML($content);

    $anchors = $dom->getElementsByTagName('a');
    $len = $anchors->length;

    if ( $len > 0 ) {
        $i = $len-1;
        while ( $i > -1 ) {
        $anchor = $anchors->item( $i );

        if ( $anchor->hasAttribute('href') ) {
            $href = $anchor->getAttribute('href');
            $regex = '/^http/';

            if ( !preg_match ( $regex, $href ) ) { 
            $i--;
            continue;
            }

            $text = $anchor->nodeValue;
            $textNode = $dom->createTextNode( $text );

            $strong = $dom->createElement('strong');
            $strong->appendChild( $textNode );

            $anchor->parentNode->replaceChild( $strong, $anchor );
        }
        $i--;
        }
    }

    echo $dom->saveHTML();
    ?>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top