【问题标题】:php html create link from textphp html从文本创建链接
【发布时间】:2011-03-09 22:00:03
【问题描述】:

我找到了一个在文本中找到链接时创建 html 链接的例程

 <?php
 function makelink($text) 
 {
 return preg_replace('/(http\:\/\/[a-zA-Z0-9_\-\.]*?) /i', '<a href="$1">$1</a> ', $text." "); 
 } 

 // works
 echo makelink ("hello how http://www.guruk.com ");

 // dont work
 echo makelink ("hello how http://www.guruk.com/test.php ");

?>

正如您在示例中看到的,它仅适用于域查找,而不是当该链接中有页面或子目录时。

您能否提供一个解决方案,让该功能也适用于页面和子目录?

谢谢 克里斯

【问题讨论】:

标签: php html text


【解决方案1】:

字符?=&amp; 用于带有查询字符串的网址。请注意,我将分隔符从 / 更改为 !,因为您的表达式中有很多斜杠。另请注意,如果您处于不区分大小写模式,则不需要 A-Z

return preg_replace('!(http://[a-z0-9_./?=&-]+)!i', '<a href="$1">$1</a> ', $text." ");

【讨论】:

    【解决方案2】:

    您的正则表达式应在其字符类中包含正斜杠以作为 url 的结尾:

    /(http\:\/\/[a-zA-Z0-9_\-\.\/]*?) /i
    

    应该这样做。

    【讨论】:

      【解决方案3】:

      没有正则表达式:

      <?php
          // take a string and turn any valid URLs into HTML links
          function makelink($input) {
              $parse = explode(' ', $input);
              foreach ($parse as $token) {
                  if (parse_url($token, PHP_URL_SCHEME)) {
                      echo '<a href="' . $token . '">' . $token . '</a>' . PHP_EOL;
                  }
              }
          }
      
          // sample data
          $data = array(
              'test one http://www.mysite.com/',
              'http://www.mysite.com/page1.html test two http://www.mysite.com/page2.html',
              'http://www.mysite.com/?go=page test three',
              'https://www.mysite.com:8080/?go=page&test=four',
              'http://www.mysite.com/?redir=http%3A%2F%2Fwww.mysite.com%2Ftest%2Ffive',
              'ftp://test:six@ftp.mysite.com:21/pub/',
              'gopher://mysite.com/test/seven'
          );
      
          // test our sample data
          foreach ($data as $text) {
              makelink($text);
          }
      ?>
      

      输出:

      <a href="http://www.mysite.com/">http://www.mysite.com/</a>
      <a href="http://www.mysite.com/page1.html">http://www.mysite.com/page1.html</a>
      <a href="http://www.mysite.com/page2.html">http://www.mysite.com/page2.html</a>
      <a href="http://www.mysite.com/?go=page">http://www.mysite.com/?go=page</a>
      <a href="https://www.mysite.com:8080/?go=page&test=four">https://www.mysite.com:8080/?go=page&test=four</a>
      <a href="http://www.mysite.com/?redir=http%3A%2F%2Fwww.mysite.com%2Ftest%2Ffive">http://www.mysite.com/?redir=http%3A%2F%2Fwww.mysite.com%2Ftest%2Ffive</a>
      <a href="ftp://test:six@ftp.mysite.com:21/pub/">ftp://test:six@ftp.mysite.com:21/pub/</a>
      <a href="gopher://mysite.com/test/seven">gopher://mysite.com/test/seven</a>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-07
        • 2013-03-07
        • 1970-01-01
        • 1970-01-01
        • 2020-12-31
        • 1970-01-01
        相关资源
        最近更新 更多