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

 

508 visitas.

36 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. Hello,

    Our company, RatingsKing, specializes in posting 5-star testimonials on all major review sites. This way people can find you much easier and get a good impression of your business.
    Just go on our website and choose the package that best fits your needs at https://ratingsking.com/packages.php

    Our packages start from $49/month.
    Depending on your package you will have a number of positive reviews that we will do for you. You will have reports monthly with the work that has been done in your account.

    Usually, we are posting on all major reviews sites or other listings you may have.

  3. We made $175,430.18 this year doing online sales from our website! You can do the same!

    What we offer:
    Instant Setup and consulting
    The methods we used
    3 Months of us helping you to get setup
    Works in all countries.

    Money back Guarantee. If you don’t make back your $499 I will refund you.

    https://shoppy.gg/product/dx1365S

  4. Biggest Ever Sale NOW!
    50% OFF On Us! With this Soft Durable Pet Padded Mattress
    ☑ 2x More Durable, Soft & Sustainable with high quality polyester materials
    ☑ Easier to Wash
    ☑ 30 Days Money Back Guarantee

    Buy now: petmattress.store

    Best Wishes,
    Rosaline

  5. 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

    Sincerely,

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

  6. Hello

    Our Medical-Grade Toenail Clippers is the safest and especially recommended for those with troubles with winding nails, hard nails, two nails, nail cracks, deep nails, thickened nails etc..

    Get yours: thepodiatrist.store

    Kind Regards,

    Lynwood

  7. Здравствуйте!
    Предлагаем самые лучшие прогоны «киллеры» для интернет-сайтов конкурента. Всего от 2000 р.
    – 100% результат. Веб-сайты точно «упадут».
    – Максимальное число отрицательных фитбеков.
    – Собрана особая база – максимально «убийственные» площадки из 10 млн. веб-ресурсов (порно, вирусы, спам и тому подобные). Это работает безотказно.
    – Прогон выполняем одновременно с четырех мощных серверов.
    – Непрерывная отправка токсичных ссылок на официальный емейл.
    – Выполнение заказа на протяжении 40-240 часов 24/7. Растянем сколько угодно по времени.
    – Прогоняем с запрещёнными ключевыми фразами.
    – При нескольких прогонах – отличные бонусы.

    Стоимость $80
    Полная отчётность.
    Оплата: Qiwi, Yandex.Money, Bitcoin, Visa, MasterCard…

    Telgrm: @exrumer
    Skype: xrumer.pro
    WhatsApp: +7(977)536-08-36

    Только эти!
    А тАкож Работаем со Студиями!

  8. SUPPER PROMOTION =>> Buy 2 get 1 free + 50% OFF

    SimpleKlean™ Groove Cleaning Brush IN MODEL 2021! PP material handle, scouring brush head, good cleaning power.
    SimpleKlean™ can clear the door and window slides and gaps, etc., convenient and effortless.
    Suitable for multiple scenes, daily household cleaning, easy and effortless.

    Get Yours: simpleklean.online

    To your success,
    Karen

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

  9. 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: fashiondaily.online

    The Best,

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

  10. EASE YOUR PAIN IN 10 MINUTES EFFORTLESSLY

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

    Shop Now: neckflexer.online

    Merry Christmas and happy new year!

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

  11. Здравствуйте, Ув. Boss!
    Предложу поднятие позиций на 10-15 пунктов в поисковиках.
    Цена всего 499 ру. Качественный ИкС. Отчётность. Любая страна.
    Прогоны сайтов от Профессионалов! Сайт действительно подымается.
    Хваленые БаЗы. Знающие борятся за каждую ссылку.
    Делаем с Любовью! Как себе.
    Contact:
    telegrm:@xrumers
    mail: Loves.Ltd@gmail.com
    Skype: Loves.Ltd
    WhatsApp: +7(977)536-08-36

  12. Good Morning

    Defrost frozen foods in minutes safely and naturally with our THAW KING™.

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

    Buy now: thawking.store

    Kind Regards,

    Josefa

  13. Good Morning

    Do you have time to brush your dog’s teeth every day?

    Let your dog clean his own teeth with our dog dental care brushing stick. Made of eco-friendly natural rubber, this toothbrush is sturdy. The soft design is safe for your dogs’ gums and helps to clean their teeth and protect them from oral diseases and dental decay.

    Act Now And Receive A Special Discount!

    Click here: https://dogcare.center

    Best,

    Phillipp

  14. WhatDroid is a breakthrough automation and scheduling App for Whatsapp that makes marketing easy for small businesses and solopreneurs.

    WhatDroid is the largest messaging application with more than 1.3 billion active users globally.

    Unlike Email with a poor and decreasing open rate, WhatsApp messages are opened at the rate of over 98%. This is also backed by serious engagement.

    https://marketingguru.sell.app/product/whatsapp-marketing

  15. 50% OFF + FREE SHIPPING!

    Introducing the Most Comfortable Headphones in the World! Seemlessly listen to your favorite music.

    Shop Here: iheadphone.online

    Best regards,

    Richie

  16. Biggest Ever Sale NOW!

    50% OFF On Us! With this Soft Durable Pet Padded Mattress
    1. 2x More Durable, Soft & Sustainable with high quality polyester materials
    2. Easier to Wash
    3. 30 Days Money Back Guarantee

    Buy now: petmattress.store

    Sincerely,
    Robbin

  17. 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

    Kind Regards,

    Louis

  18. Hey.

    We know the pandemic has hit all companies hard and we are all recovering.

    We want to help! We made our bulk WhatsApp Sender available for $5.

    This offer is valid only for today (17 January 2022).

    Lets get business rolling again.

    You can view it here: https://cutt.ly/BulkSender

    «You can have a good product and bad marketing and fail or a bad product and good marketing and succeed»

  19. Good Morning

    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: linterna.store

    Enjoy,

    Emil

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *