PHP 通过正则表达式匹配从文本中生成超链接


PHP make hyperlink from text by regex match

我有一个脚本,可以使句子中的链接(http,https和www)可点击。问题是我只能有一个链接。我可以通过任何类型的 if 语句中的循环来解决此问题吗?

$text = "Both www.google.com and http://www.google.com/calendar/ are links";
/**
* Make clickable links from URLs in text.
*/
function make_clickable($text) {
  // Force http to www.
  $text = preg_replace( "(www'.)", "http://www.", $text );
  // Delete duplicates after force.
  $text = preg_replace( "(http://http://www'.)", "http://www.", $text );
  $text = preg_replace( "(https://http://www'.)", "https://www.", $text );
  // The RegEx.
  $regExUrl = "/(http|https)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/'S*)?/";
  // Check if there is a URL in the text.
  if(preg_match($regExUrl, $text, $url)) {
    // Make the URLs hyper links.
    $text = preg_replace(
      $regExUrl,
      '<a href="' . $url[0] . '" target="_blank">' . $url[0] . '</a>',
      $text
    );
  }    
  return $text;
}
echo make_clickable($text);

结果:http://www.google.com 和 http://www.google.com 都是链接

提前谢谢。

你不需要任何循环。试试这个:

/**
* Make clickable links from URLs in text.
*/
    function make_clickable($text) {
      // Force http to www.
      $text = preg_replace( "(www'.)", "http://www.", $text );
      // Delete duplicates after force.
      $text = preg_replace( "(http://http://www'.)", "http://www.", $text );
      $text = preg_replace( "(https://http://www'.)", "https://www.", $text );
      // The RegEx.
      $regExUrl = "/(http|https)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/'S*)?/";
      // Check if there are URLs in the text then replace all
      $text = preg_replace_callback($regExUrl, function($matches) {
            return '<a href="' . $matches[0] . '" target="_blank">' . $matches[0] . '</a>';
      }, $text);
      return $text;
    }

参考: preg_replace_callback()