0

私はこれについて何時間も頭を悩ませてきました。いくつかのhtmlを関数に渡し、リンクを置き換えて、置き換えられたリンクでhtmlを返す必要があります。

<?php
    final static public function replace_links($campaign_id, $text) {
        $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
        if(preg_match_all("/$regexp/siU", $text, $matches, PREG_SET_ORDER)) {
            foreach($matches as $match) {
                if(substr($match[2], 0, 2) !== '##') {  //  ignore the placeholders
                    if(substr($match[2], 0, 6) !== 'mailto') {  //  ignore email addresses
                        // $match[2] = link address
                        // $match[3] = link text
                        $url = "http://xxx.com/click?campaign_id=$campaign_id&email=##email_address##&next=" . $match[2];
                        #$text .= str_replace($match[2], $url, $text);
                        #echo $links . "\n";
                        preg_replace($match[2], "<a href='$url'>{$match[3]}</a>", $match[2]);
                    }
                }
                return $text;
            }
        }
    }
?>

リンクをエコーすると、一致したすべてのリンクが表示されます。問題は、以下の置換されたリンクの例で完全な HTML を返す方法です。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<a href="mailto:sssss">xxxx</a>
<a href="http://www.abc.com/">xxxx</a>
<a href="http://www.google.com/yeah-baby-yeah">xxxx</a>
</body>
</html>

次のようになる必要があります。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<a href="mailto:sssss">xxxx</a>
<a href="https://xxx.com/click?next=http://www.abc.com/">xxxx</a>
<a href="https://xxx.com/click?next=http://www.google.com/yeah-baby-yeah">xxxx</a>
</body>
</html>

これが理にかなっていることを願っています。

前もって感謝します、

カイル

4

2 に答える 2

0

車輪の再発明をしないでください。次のようなものを使用してください。

http://code.google.com/p/jquery-linkify/

私も使うのは本当に簡単です

于 2012-04-03T19:42:26.460 に答える
0

preg_replace についてはよくわかりませんが、あなたとまったく同じ機能が必要でした。行の変更:

preg_replace($match[2], "<a href='$url'>{$match[3]}</a>", $match[2]);

このため:

str_replace($match[0],$url,$text);

トリックを行うようです。

この関数から戻り値を取得する必要があっただけなので、次のようになります。

//$text = preg_replace($match[2], "<a href='$url'>{$match[3]}</a>", $match[2]);
$text = str_replace($match[0],$url,$text);
于 2012-08-15T15:40:17.850 に答える