PHP: find links in a string and replace them with actual html link tags

Blog / PHP ·

Currently I'm working on an application that gets data from Twitter. The tweet's string contains links that have to be transformed into html link tags. Here is a simple PHP function that helped me.

function makeLinks($str) {
  $reg_exUrl = "/(http|https|ftp|ftps)\\:\\/\\/[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]{2,3}(\\/\\S*)?/";
  $urls = array();
  $urlsToReplace = array();
  if (preg_match_all($reg_exUrl, $str, $urls)) {
      $numOfMatches = count($urls[0]);
      $numOfUrlsToReplace = 0;
      for ($i = 0;$i < $numOfMatches;$i++) {
          $alreadyAdded = false;
          $numOfUrlsToReplace = count($urlsToReplace);
          for ($j = 0;$j < $numOfUrlsToReplace;$j++) {
              if ($urlsToReplace[$j] == $urls[0][$i]) {
                  $alreadyAdded = true;
              }
          }
          if (!$alreadyAdded) {
              array_push($urlsToReplace, $urls[0][$i]);
          }
      }
      $numOfUrlsToReplace = count($urlsToReplace);
      for ($i = 0;$i < $numOfUrlsToReplace;$i++) {
          $str = str_replace($urlsToReplace[$i], "<a href=\\"".$urlsToReplace[$i]."\\">" . $urlsToReplace[$i] . "</a> ", $str);
      }
      return $str;
  } else {
      return $str;
  }
}

Krasimir Tsonev With over two decades of deep programming expertise, I offer comprehensive web consultancy and stack audits, alongside specialized workshops, training, and engaging public speaking to elevate your team's skills and optimize your digital presence. Contact me.

Keywords: urlstoreplace str numofurlstoreplace urls alreadyadded numofurlstoreplace count urlstoreplace html link tags
Share the post on Twitter, Facebook, LinkedIn