PHP在正则表达式中的匹配上调用函数

时间:2011-09-17 23:32:41

标签: php regex

我需要对字符串中的所有电子邮件地址进行加密/编码,将它们转换为链接并保留其余字符串完整无缺?

我正在使用

$withlinks = preg_replace("/([\w-?&;#~=\.\/]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))/i","<a href=\"mailto:$1\">$1</a>",$nolinks);

从电子邮件中建立链接

function encode_email($str) {
    $str = mb_convert_encoding($str , 'UTF-32', 'UTF-8'); //big endian
    $split = str_split($str, 4);

    $res = "";
    foreach ($split as $c) {
        $cur = 0;
        for ($i = 0; $i < 4; $i++) {
            $cur |= ord($c[$i]) << (8*(3 - $i));
        }
        $res .= "&#" . $cur . ";";
    }
    return $res;
}

对地址进行编码,但我无法弄清楚如何将它们放在一起,这样只有电子邮件才会被编码并变成链接。

1 个答案:

答案 0 :(得分:1)

您可以使用preg_replace_callback,以便您可以操作替换文字,使其完全符合您的要求......

  <?php

// test string
$nolinks = "amy@winehous.com is an email for bobby@fisher.com plays chess";

// your original function
function encode_email($str)
{
    $str = mb_convert_encoding($str, 'UTF-32', 'UTF-8'); //big endian
    $split = str_split($str, 4);

    $res = "";
    foreach ($split as $c) {
        $cur = 0;
        for ($i = 0; $i < 4; $i++) {
            $cur |= ord($c[$i]) << (8 * (3 - $i));
        }
        $res .= "&#" . $cur . ";";
    }
    return $res;
}

// function used for callback 
function encode_email_and_add_link($in)
{
    // get encoded email address (don't actually know what this function does)
    $encoded = encode_email($in[1]);
    // return a hyperlink string built with encoded email address
    return "<a href=\"mailto:$encoded\">$encoded</a>";
}

// do the regex with callback
$withlinks = preg_replace_callback("/([\w-?&;#~=\.\/]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))/i", 'encode_email_and_add_link', $nolinks);

// output the results
echo $withlinks;