Replacing Plain Text Links to HTML Anchor Tag in PHP Tutorial
In this tutorial, we will tackle about Replacing the Plain Text Links of a content with an Anchor Tag of HTML using PHP. We will be using the PHP's preg_replace() function. For those who dont have any idea about the preg_replace, this function replace all the occurence of a string that matches the given pattern to your desired format or replacement string.
We will be creating a simple PHP Web App that is able to save content to the database. The simple app will automatically replace the plain text links from the content with a clickable link that can redirect users to the link's page. I will be using Bootstrap and XAMPP as my local webserver to create and run the tutorial code.
Creating the Database
Create a new Database naming simple_db. Then, navigate to the SQL Tab of the database and ccopy/paste the SQL script below to create the contents table and insert the sample data.
- (1, 'This a sample Content that contains a plain text that will be Replaced into an anchor tag when display on the list\r\n\r\nThe Sample Links are:\r\nhttps://sourcecodester.com , www.google.com, and facebook.com,');
Creating the Interface
The script below is the code for our simple application interface. This includes also the form of create the contents. Save this file as index.php.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="Font-Awesome-master/css/all.css">
- <link rel="stylesheet" href="css/bootstrap.css">
- <style>
- a {
- color: #0d6efd;
- text-decoration: underline;
- max-width: 100%;
- word-break: break-all;
- }
- </style>
- </head>
- <body class="">
- <nav class="navbar navbar-expand-lg navbar-light bg-light">
- <div class="container">
- </div>
- </nav>
- <div class="container py-5 h-100">
- <div class="row">
- <div class="col-lg-12">
- </div>
- </div>
- <hr>
- <div class="row">
- <div class="col-lg-4">
- <form action="./" method="POST" class="form-group">
- <div class="form-group mb-2">
- </div>
- <div class="form-group">
- </div>
- </form>
- </div>
- <div class="col-lg-8">
- <!-- content List -->
- <ul class="list-group">
- <li class="list-group-item">
- <!-- Content -->
- </li>
- </ul>
- </div>
- </div>
- </div>
- </body>
- </html>
Creating Database Connection
The code below is our database connection for saving and fetching the data on the database. Paste the code below in the beginning line of your index.php file.
- $conn= new mysqli('localhost','root','','sample_db');
- if(!$conn){
- echo "Database Connection Failed. Error: ".$conn->error;
- exit;
- }
Creating the Save Query
The code below is the PHP Script that saving or inserting the data on the database. Psete the code below the database connection sript.
- if($_SERVER['REQUEST_METHOD'] == 'POST'){
- $save = $conn->query("INSERT INTO `contents` (`content`) VALUE('{$content}')");
- if($save)
- echo "<script> alert('Content successfully saved.'); location.replace('./');</script>";
- else
- "<script> alert('Saving content failed. Error: ".$conn->error."');</script>";
- }
Fetching Data from Database
The code below is the script that displays the list of contents from the database. This contains the main goal of this tutorial which is converting or replacing the plain text links with HTML anchor tag. Paste the code below inside the "unorederd list" tag
- <?php
- $query=$conn->query("SELECT * FROM `contents` order by `id` asc");
- while($row = $query->fetch_assoc()):
- $regEx= "/(?<=:|)(?:https:\/\/|http:\/\/)?(?:[a-zA-Z0-9]{0,}\.|)?([a-zA-Z0-9-_]{0,}\.[a-zA-Z\/\-\_%\+\&\?\=0-9]{0,})/";
- $replacement = "<a href='//$0' target='_blank'>$0</a>";
- ?>
- <li class="list-group-item">
- </li>
- <?php endwhile; ?>
That's it. The simple web app is only written in a sinlge PHP file.
Here's the Full Source Code.
index.php- <?php
- $conn= new mysqli('localhost','root','','sample_db');
- if(!$conn){
- echo "Database Connection Failed. Error: ".$conn->error;
- exit;
- }
- if($_SERVER['REQUEST_METHOD'] == 'POST'){
- $save = $conn->query("INSERT INTO `contents` (`content`) VALUE('{$content}')");
- if($save)
- echo "<script> alert('Content successfully saved.'); location.replace('./');</script>";
- else
- "<script> alert('Saving content failed. Error: ".$conn->error."');</script>";
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Replacing Plain Text Links</title>
- <link rel="stylesheet" href="Font-Awesome-master/css/all.css">
- <link rel="stylesheet" href="css/bootstrap.css">
- <script src="js/bootstrap.js"></script>
- <style>
- a {
- color: #0d6efd;
- text-decoration: underline;
- max-width: 100%;
- word-break: break-all;
- }
- </style>
- </head>
- <body class="">
- <nav class="navbar navbar-expand-lg navbar-light bg-light">
- <div class="container">
- <a class="navbar-brand" href="//www.sourcecodester" target="_blank">SourceCodester</a>
- </div>
- </nav>
- <div class="container py-5 h-100">
- <div class="row">
- <div class="col-lg-12">
- <h3 class="text-center">Replacing Link Plain Text with HTML "a" Tag. </h3>
- </div>
- </div>
- <hr>
- <div class="row">
- <div class="col-lg-4">
- <form action="./" method="POST" class="form-group">
- <div class="form-group mb-2">
- <label for="content" class="control-label">Content</label>
- <textarea name="content" id="content" cols="30" rows="4" class="form-control rounded-0" required></textarea>
- </div>
- <div class="form-group">
- <button class="btn btn-sm btn-flat btn-primary">Save</button>
- </div>
- </form>
- </div>
- <div class="col-lg-8">
- <ul class="list-group">
- <?php
- $query=$conn->query("SELECT * FROM `contents` order by `id` asc");
- while($row = $query->fetch_assoc()):
- $regEx= "/(?<=:|)(?:https:\/\/|http:\/\/)?(?:[a-zA-Z0-9]{0,}\.|)?([a-zA-Z0-9-_]{0,}\.[a-zA-Z\/\-\_%\+\&\?\=0-9]{0,})/";
- $replacement = "<a href='//$0' target='_blank'>$0</a>";
- ?>
- <li class="list-group-item">
- </li>
- <?php endwhile; ?>
- </ul>
- <?php if($query->num_rows <= 0): ?>
- <center>No Content Listed Yet.</center>
- <?php endif; ?>
- </div>
- </div>
- </div>
- </body>
- </html>
That's it! I hope this simple tutorial will help you with what you and for your future PHP Project. Explore more on this website for more Tutorials and Free Source Codes.
Enjoy Coding :))Add new comment
- 928 views