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:

enlace-formateado-comentario

 

521 visitas.

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

  1. Hi,

    Do you know that your WordPress site muchocodigo.com 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? : http://swella.xyz/AoECM

    Best Regards,

    Alton

  2. Здравствуйте ув. Boss!
    Предложу поднятие Вашего сайта на 10-15 пунктов позиций.
    В поисковиках Яндекс/Google. Domain Rating.
    Цена всего 880 ру. Качественный ИкС.
    Прогоны сайтов от Профессионалов!
    Хваленые БаЗы. Отчётность.
    Contact:
    telegram:@exrumer
    mail: Loves.Ltd@gmail.com
    Skype: Xrumer.pro
    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.

    Best,
    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: https://thebackpack.sale

    Best regards,

    Rena

  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. BulletProofSMTP.org

  6. ZippyLeads.org 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 TopDataList.com is shutting down.

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

    Visit us on TopDataList.com

  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: hineck.online

    The Best,

    Michale
    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: https://fashionbag.sale

    Best,

    Felipa

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

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

    Regards,
    Lauren

  11. С радостью приветствуем вас!
    Рекомендуем самые лучшие прогоны «киллеры» для веб-сайтов конкурента. Всего от 2000 руб.
    – Стопроцентный эффект. Онлайн-сайты конкурентов «умрут».
    – Наибольшее количество отрицательных фитбеков.
    – Собрана специфическая база – самые сильные площадки из 10 млн. веб-сайтов (вирусных, спамных, порно и тому подобных). Это работает безотказно.
    – Прогон производим сразу с 4 мощных серверов.
    – Постоянная отправка вирусных ссылок на электронный ящик.
    – Выполнение заказа на протяжении 40-240 часов сутки напролет. Растянем по времени как угодно.
    – Прогон с запретными ключами.
    Телегрм: @exrumer
    Skype: xrumer.pro
    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: https://bangeonline.shop

    Sincerely,

    Brittany

  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:
    https://youtu.be/SQHFveYdjV8

    Kind Regards,
    Jane

  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: https://caredogbest.com

    FREE Shipping – TODAY ONLY!

    The Best,

    Elma

  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: https://medicopostura.com

    FREE Shipping – TODAY ONLY!

    Thank You,

    Alana

Deja una respuesta

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