Formatear Urls en comentarios de un blog con PHP

Es habitual tener sistemas de comentarios en nuestras páginas y blogs, ya sean propios o de terceros, que insertan los comentarios de los usuarios en modo de texto, de forma que cuando estos introducen una url o link, este no es clickable. De hay que sea buena idea formatear/parsear esas urls para convertirlas en links.

Tenemos dos posibles vías de hacerlo, una es grabar el comentario en la Base de Datos con los links formateados y otra es grabarlo tal cual lo pusieron y a la hora de mostrarlo, formatear los links, en ambos casos hay que procesar el texto del comentario para detectar enlaces y convertirlos.

Para ello, propongo el siguiente código, que si bien se puede condensar en menos líneas, lo muestro a pasos por cuestiones didácticas:

$reg_exUrl = "/((((http|https)\:\/\/)|www\.)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}(\/\S*)?)/";
$comentario =  preg_replace( $reg_exUrl, "<a rel='nofollow' href=\"$1\">$1</a> ", $comentario );
$comentario = str_replace("<a rel='nofollow' href=\"www", "<a rel='nofollow' href=\"http://www", $comentario);
$comentario = str_replace(">http://", ">", $comentario);
$comentario = str_replace(">https://", ">", $comentario);
$comentario = str_replace(">www.", ">", $comentario);
$comentario = str_replace("%20", " ", $comentario);    

Comenzamos con una expresión regular que nos identifica en el texto las partes que cumplan el patrón de una url, para acto seguido introducir por delante y detrás de esas partes el etiquetado típico de un link.

El link lo fijamos como rel=’nofollow’, ya que es un sistema de comentarios, mucha gente sólo escribe para promocionar sus webs, y no es necesario estar cediendo PageRank a infinidad de páginas que ni conocemos personalmente.

La 3ª línea la ponemos para evitar urls que no incorporen http:// delante, pues de lo contrario y dependiendo de la programación de cada web, es posible que al hace click al link, este intentase cargarse desde la url relativa desde donde se muestra, lo cual no es precisamente lo que se desea.

Las 4 últimas líneas son sólo para embellecer el texto del enlace mostrado, es decir, cuestiones meramente estéticas, quitarle el inicio de la url y poner espacios en vez de su equivalente %20

Y así nos quedaría un link una vez formateado:



525 visitas.

37 comentarios sobre “Formatear Urls en comentarios de un blog con PHP

  1. Hi,

    Do you know that your WordPress site is very slow to load and that you lose visitors, leads and customers every day?

    We have already optimized more than 2000 sites since 2015, why not yours? :

    Best Regards,


  2. Здравствуйте ув. Boss!
    Предложу поднятие Вашего сайта на 10-15 пунктов позиций.
    В поисковиках Яндекс/Google. Domain Rating.
    Цена всего 880 ру. Качественный ИкС.
    Прогоны сайтов от Профессионалов!
    Хваленые БаЗы. Отчётность.
    WhatsApp: +7(977)536-08-36

  3. Hello,

    I’ve been an reader of your blog for some time now, and I enjoy reading your blog on a regular basis.

    Recently I’ve been researching an idea for a blog post about human hair wigs – and then I thought that this could be a great contribution for your audience.
    I’ll make sure the piece overflows with information that can’t be found anywhere else.

    What do you think? Should I write it up and send you a draft?
    Here are some topics you maybe interested:
    [What are the different types of human hair wigs?]
    [What do I need to know about human hair wigs?]
    [What is the best human hair wig?]

    I look forward to hearing from you soon.

    Newigstyle Team

  4. New Multifunction Waterproof Backpack

    The best ever SUPER Backpack: Drop-proof/Scratch-resistant/USB Charging/Large capacity storage

    50% OFF for the next 24 Hours ONLY + FREE Worldwide Shipping for a LIMITED time

    Buy now:

    Best regards,


  5. Hello.

    We are offering Bullet Proof SMTP servers that never get suspended. Email as much as you want.

    DMCA ignored, bulletproof locations, 100% uptime guaranteed, unlimited data transfer, and 24/7/365 support.

    100 Spots available.

  6. is running an easter special till the 18th of April.

    Get all the leads you need for your company with our easter special.

  7. Hello.

    It is with sad regret to inform you is shutting down.

    We have made all our databases available for you for a once off fee.

    Visit us on

  8. World’s Best Neck Massager Get it Now 50% OFF + Free Shipping!

    Wellness Enthusiasts! There has never been a better time to take care of your neck pain!

    Our clinical-grade TENS technology will ensure you have neck relief in as little as 20 minutes.

    Get Yours:

    The Best,

    Formatear Urls en comentarios de un blog con PHP – Compartiendo codigo…

  9. Good Morning

    Don’t you hate carrying a big bulky backpack when you are only going out for the day? This high quality shoulder bag solves that problem.
    Carry enough without bogging yourself down! Perfect for that fishing trip or day hike!

    50% OFF for the next 24 Hours ONLY + FREE Worldwide Shipping for a LIMITED time

    Buy now:



  10. Hello, from we are a provider of unique databases that could help your business.

    Please visit us at to see if we can help you.


  11. С радостью приветствуем вас!
    Рекомендуем самые лучшие прогоны «киллеры» для веб-сайтов конкурента. Всего от 2000 руб.
    – Стопроцентный эффект. Онлайн-сайты конкурентов «умрут».
    – Наибольшее количество отрицательных фитбеков.
    – Собрана специфическая база – самые сильные площадки из 10 млн. веб-сайтов (вирусных, спамных, порно и тому подобных). Это работает безотказно.
    – Прогон производим сразу с 4 мощных серверов.
    – Постоянная отправка вирусных ссылок на электронный ящик.
    – Выполнение заказа на протяжении 40-240 часов сутки напролет. Растянем по времени как угодно.
    – Прогон с запретными ключами.
    Телегрм: @exrumer
    WhatsApp: +7(977)536-08-36
    icq: 5688885
    Только Эти!

  12. Hello,

    I hope you’re doing well. I wanted to let you know about our new BANGE backpacks and sling bags that just released.

    The bags are waterproof and anti-theft, and have a built-in USB cable that can recharge your phone while you’re on the go.

    Both bags are made of durable and high-quality materials, and are perfect for everyday use or travel.

    Order yours now at 50% OFF with FREE Shipping:



  13. Hi there,

    Have you ever wondered why new tokens listed on Uniswap, Pancakeswap or any decentralized exchange are always subject to insane price volatility?

    Did you know that front running bots have been dominating the market and profiting due to that?

    Check out our new Youtube video for a free and detailed tutorial on how to deploy your own front running bot:

    Kind Regards,

  14. Hello

    I wanted to reach out and let you know about our new dog harness. It’s really easy to put on and take off – in just 2 seconds – and it’s personalized for each dog.
    Plus, we offer a lifetime warranty so you can be sure your pet is always safe and stylish.

    We’ve had a lot of success with it so far and I think your dog would love it.

    Get yours today with 50% OFF:

    FREE Shipping – TODAY ONLY!

    The Best,


  15. Good Morning

    I understand that you are looking for ways to improve your posture and contribute to a healthy lifestyle. I think our product, Medico Postura™ Body Posture Corrector, can be of great help.

    Medico Postura™ helps improve your posture INSTANTLY. It is an easy-to-use device that you can wear at home, work, or even when you are sleeping.

    It is made of lightweight and breathable fabric, making it comfortable to wear all day long.

    Get it today while it’s still 60% OFF:

    FREE Shipping – TODAY ONLY!

    Thank You,



    Be Free from Neck Pain
    Try NeckFlexer & Relieve Neck Pain Effortlessly In 10 Min!
    Save 50% OFF + FREE Worldwide Shipping

    Shop Now:

    Compartiendo codigo… – Programación y ejemplos de código

  17. Доброго утра!
    Хотим предложить самые лучшие прогоны «убийцы» для сайтов ваших конкурентов. Всего от 2000 рублей.
    – Гарантированный эффект. Онлайн-сайты конкурентов «умрут».
    – Наибольшее число негативных фитбеков.
    – Наша специальная база – выжимка самых «убийственных» площадок из 10 000 000 онлайн-ресурсов (вирусные, спамные, порно и тому подобные). Это действует бесперебойно.
    – Прогон осуществляется одновременно с 4-х мощных серверов.
    – Непрерывный спам активационных ссылок на официальный email.
    – Выполнение в течение 40-240 часов. Можем растянуть по времени сколько угодно.
    – Прогон с запрещёнными ключами.
    Telgrm: @exrumer
    WhatsApp: +7(977)536-08-36
    icq: 5688885
    Только Эти!

  18. Morning,

    I hope you’re well. I am excited to tell you about our Full Body Resistance Band Kit that can help you get an amazing workout without having to go to the gym.
    This is the best and cheapest athletic gear on the market. You can do a full body workout from the comfort of your home.

    I believe that this product can help you reach your fitness goals.

    Save 50% OFF + FREE Worldwide Shipping
    Shop Now:

    To your success,


  19. Hi there,

    Have you ever wondered why new cryptocurrency tokens are always subject to insane price action?

    We are giving away a totally free step-by-step guide on how you can profit from that with a front running bot.

    Check out our new Youtube video to learn how to deploy your own bot without any coding experience:

    Kind Regards,

    Telephone: (888) 850-1556

  20. New Multifunction Anti-theft Waterproof Sling Bag

    The best ever SUPER Sling Bag: Drop-proof/Anti-theft/Scratch-resistant/USB Charging

    50% OFF for the next 24 Hours ONLY + FREE Worldwide Shipping for a LIMITED time

    Buy now:

    To your success,

    Compartiendo codigo… – Programación y ejemplos de código

  21. Добрый день!
    Выполняем лучшие «убийственные» прогоны для сайтов конкурентов. Всего от 2000 руб.
    – Гарантированный результат. Сайты конкурентов «упадут».
    – Наибольшее число негативных фитбеков.
    – Собрана специальная база – выжимка самых сильных площадок из 10 млн. интернет-ресурсов (порно, вирусных, спамных и т.д.). Это работает бесперебойно.
    – Прогон делаем одновременно с четырех мощных серверов.
    – Постоянный спам активационных ссылок на официальный e-mail.
    – Можем растянуть как угодно по времени.
    – Прогон с запретными ключевыми фразами.
    Телегрм: @exrumer
    WhatsApp: +7(977)536-08-36
    icq: 5688885
    Только Эти!

  22. Get The Worlds Greatest Magic Sand Free Beach Mat!

    Watch sand, dirt & dust disappear right before your eyes! It’s perfect for beach, picnic, camping or hiking.

    Act Now And Receive A Special Discount For Our Magic Mat!

    Get Yours Here:

    Thank You,


  23. Hey, did you know that you can use robots to build all of the content on your website in just a few clicks? I thought you might want to check out it’s free to try as well.

  24. Hello, did you know that there are 241,120 internet directories in the world.

    These websites are what drive traffic to YOUR business.

    Want more traffic? Want more Sales? We can help – today.

    Your website is listed in only 44 of these directories.

    Get more traffic for your Global audience.

    Our automated system adds your website to all of the directories.

    You can find it here:

    Act today, and we will expedite your listings and waive the processing charge!

  25. Good day

    The New Powerful LED Flashlight is The Perfect Flashlight For Any Situation!

    The 3,000 Lumens & Adjustable Zoom gives you the wide field of view and brightness other flashlights don’t have.

    50% OFF + Free Shipping! Get it Now:



Responder a Isaac Burton Cancelar la respuesta

Tu dirección de correo electrónico no será publicada.