请问用preg_replace用用户定义的字符串替换<a href="#">sometext+url </a>?

时间:2011-06-16 07:34:32

标签: php html regex

我该如何替换

<a href="#" >sometext+url </a> with url by using preg_replace

我使用了这个功能

function parse_url($url) {
    $url = preg_replace("#<a\s*[^>]*href=\"#i", "<url>", $url,-1);
    $url = preg_replace("<\a>", "<url>", $url,-1);
    return $url;
}

2 个答案:

答案 0 :(得分:1)

<?php
function replaceAnchorsWithText($data) {
    /**
     * Had to modify $regex so it could post to the site... so I broke it into 6 parts.
     */
    $regex  = '/(<a\s*'; // Start of anchor tag
    $regex .= '(.*?)\s*'; // Any attributes or spaces that may or may not exist
    $regex .= 'href=[\'"]+?\s*(?P<link>\S+)\s*[\'"]+?'; // Grab the link
    $regex .= '\s*(.*?)\s*>\s*'; // Any attributes or spaces that may or may not exist before closing tag 
    $regex .= '(?P<name>\S+)'; // Grab the name
    $regex .= '\s*<\/a>)/i'; // Any number of spaces between the closing anchor tag (case insensitive)

    if (is_array($data)) {
        // This is what will replace the link (modify to you liking)
        $data = "{$data['name']}({$data['link']})";
    }
    return preg_replace_callback($regex, 'replaceAnchorsWithText', $data);
}

$input  = 'Test 1: <a href="http: //php.net1">PHP.NET1</a>.<br />';
$input .= 'Test 2: <A name="test" HREF=\'HTTP: //PHP.NET2\' target="_blank">PHP.NET2</A>.<BR />';
$input .= 'Test 3: <a hRef=http: //php.net3>php.net3</a><br />';
$input .= 'This last line had nothing to do with any of this';

echo replaceAnchorsWithText($input).'<hr/>';
?>

此功能将输出:

Test 1: PHP.NET1(http: //php.net1).
Test 2: PHP.NET2(HTTP: //PHP.NET2).
Test 3: php.net3 (is still an anchor)
This last line had nothing to do with any of this

此代码来自php docs本身

答案 1 :(得分:0)

<?php
function subanchor($url) {

    return preg_replace("#<a\s*[^>]*href=\"(.*)\".*>(.*)</a>#i", "<url>\\1+\\2</url>", $url);
}

echo subanchor($argv[1]);
?>

$ php subacnchor.php  '<a href="http://hello.com/">trololol</a>' 
<url>http://hello.com/+trololol</url>