开发者

PHP Calling a function on matches in regexp

I need to scramble/encode all e-mail addresses in a string, tur开发者_如何学Gon them into links and leave the rest of the string intact?

I'm using

$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);

to make links out of e-mails and

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

to encode the addresses but I can't figure out how to put them together, so that only e-mails would be encoded and turned into links.


You can use preg_replace_callback so that you can manipulate the replacement text to be exactly what you want...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜