zoukankan      html  css  js  c++  java
  • PHP自动添加http://头 转换网址为链接

    有时候,当我们需要用户输入网址的时候,一般我们会让用户省略掉"http://",当提交完成后用代码自动再加上http://,若有需要,我们 还可将网址转换成链接的形式,类似于众多网页编辑器里的功能,以下代码将实现这类功能。先来看自动添加"http://"头的代码:

    自动添加"http://"头的PHP函数代码:

    <?php
    if (!preg_match("/^(http|ftp):/", $_POST['url'])){
       $_POST['url'] = 'http://'.$_POST['url'];
    }
    ?>

    PHP将网址字符串转换成超级链接,可将URL和E-mail 地址字符串转换为可点击的超级链接:

    <?php
    function makeClickableLinks($text) {
     $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)',
     '<a href="1">1</a>', $text);
     $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',
     '1<a href="http://2">2</a>', $text);
     $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',
     '<a href="mailto:1">1</a>', $text);
    return $text;
    }
    ?>

    将这两段代码结合起来,可形成以下用法:

    <?php
    $_POST['url']="www.codefans.net";
    if (!preg_match("/^(http|ftp):/", $_POST['url'])) {
       $url = 'http://'.$_POST['url'];
    }
    echo makeClickableLinks($url);
    ?>

    最终效果是把www.codefans.net加上了http://,并实现链接的形式。

  • 相关阅读:
    Python 字符串(一)
    UVA 11552 四 Fewest Flops
    UVA 10534 三 Wavio Sequence
    UVA 1424 二 Salesmen
    UVA 11584 一 Partitioning by Palindromes
    CodeForces 549G Happy Line
    CodeForces 451C Predict Outcome of the Game
    CodeForces 567C Geometric Progression
    CodeForces 527B Error Correct System
    CodeForces 552C Vanya and Scales
  • 原文地址:https://www.cnblogs.com/phpfensi/p/4333502.html
Copyright © 2011-2022 走看看