문제

내가 노력하는 경기 <a> 태그 내에서 콘텐츠 및 교체를 다음으로 텍스트 링크에 의해 다음 url 에 대괄호에 대한 인쇄 버전입니다.다음 예에서 작동하는 경우에만 있다"href".는 경우 <a> 담 또 다른 특성과 일치하 너무 많은 반환 하지 않은 원하는 결과입니다.을 어떻게 해야 일치시킬 수 있습니까 URL 링크를 텍스트와 그?

여기에는 나의 코드:

<?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;
?> 

원하는 결과:

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

감사합니다, Jason

도움이 되었습니까?

해결책

당신은 경기를 불충분하게 만들 수 있습니다 ?. 또한 이전에 속성이있을 수 있습니다. href 기인하다.

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

다른 팁

당신이 사용해야 DOM 분석 HTML,지 않을 정규 표현식을...

편집:업데이트 코드를 간단한 정규 표현식 파싱에 href 특성 값입니다.

편집#2:어는 루프 회귀할 수 있도록 핸들러 대체합니다.

$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();
    ?>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top