【问题标题】:HOw to replace <a href="#" >sometext+url </a> with user defined string using preg_replace?如何使用 preg_replace 将 <a href="#" >sometext+url </a> 替换为用户定义的字符串?
【发布时间】:2011-06-16 07:34:31
【问题描述】:

如何替换

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

【问题讨论】:

  • @Ignacio 接受的答案是错误的。请不要将人们链接到它。现代正则表达式可以解析 HTML。在大多数情况下你只是不想这样做,因为它很脆弱,解析 HTML 是一个已解决的问题。
  • 我不明白你在做什么。您希望锚元素成为 url 元素吗?是这样吗?

标签: php html regex


【解决方案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 本身

【讨论】:

    【解决方案2】:
    <?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>
    

    【讨论】:

      猜你喜欢
      • 2015-10-16
      • 2023-03-27
      • 2011-10-27
      • 2014-07-13
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      相关资源
      最近更新 更多