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.
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
Здравствуйте ув. Boss!
Предложу поднятие Вашего сайта на 10-15 пунктов позиций.
В поисковиках Яндекс/Google. Domain Rating.
Цена всего 880 ру. Качественный ИкС.
Прогоны сайтов от Профессионалов!
Хваленые БаЗы. Отчётность.
Contact:
telegram:@exrumer
mail: Loves.Ltd@gmail.com
Skype: Xrumer.pro
WhatsApp: +7(977)536-08-36
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
Hi there
Are you Scrambling while opening Jars, Bottles, and Cans?
This Jar Opener Takes The Strain & Frustration Out Of Opening Jars & Bottles! Never Struggle with opening a jar again!
Click Now & GET 50% OFF → https://kitchenopener.biz
Regards,
Kazuko
I called you 2 times. Why didn’t you pick up? I’m horny.. Please call me.
I’m online. You can chat with me by clicking this link.
https://telegra.ph/Chat-With-Me-04-02
If you ever need more social audience for muchocodigo.com, we can run Facebook Traffic campaigns with this service: https://www.seo-treff.de/product/country-targeted-traffic/
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
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
Hi there
PawSafer™ Can Safely Trim Your Dog’S Nails In No Time From Home.
Get it while it’s still 50% OFF + FREE Shipping
Buy here: https://pawsafer.shop
Regards,
Magaret
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.
I called you 2 times. Why didn’t you pick up? I’m horny.. Please call me.
I’m online. You can chat with me by clicking this link.
https://live-sex-chat.club/
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
I called you 2 times. Why didn’t you pick up? I’m horny.. Please call me.
I’m online. You can chat with me by clicking this link.
https://live-sex-chat.club/
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…
Hi there
Do you want to get backlinks from domains that have tons of ranking keywords?
https://www.monkeydigital.co/semrush-backlinks/
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
Hey
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: https://thawking.store
All the best,
Regan
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
С радостью приветствуем вас!
Рекомендуем самые лучшие прогоны «киллеры» для веб-сайтов конкурента. Всего от 2000 руб.
– Стопроцентный эффект. Онлайн-сайты конкурентов «умрут».
– Наибольшее количество отрицательных фитбеков.
– Собрана специфическая база – самые сильные площадки из 10 млн. веб-сайтов (вирусных, спамных, порно и тому подобных). Это работает безотказно.
– Прогон производим сразу с 4 мощных серверов.
– Постоянная отправка вирусных ссылок на электронный ящик.
– Выполнение заказа на протяжении 40-240 часов сутки напролет. Растянем по времени как угодно.
– Прогон с запретными ключами.
Телегрм: @exrumer
Skype: xrumer.pro
WhatsApp: +7(977)536-08-36
icq: 5688885
Только Эти!
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
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
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
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
Hello there
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: https://thepodiatrist.shop
Best,
Alvin
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
Damaris
Compartiendo codigo… – Programación y ejemplos de código
Доброго утра!
Хотим предложить самые лучшие прогоны «убийцы» для сайтов ваших конкурентов. Всего от 2000 рублей.
– Гарантированный эффект. Онлайн-сайты конкурентов «умрут».
– Наибольшее число негативных фитбеков.
– Наша специальная база – выжимка самых «убийственных» площадок из 10 000 000 онлайн-ресурсов (вирусные, спамные, порно и тому подобные). Это действует бесперебойно.
– Прогон осуществляется одновременно с 4-х мощных серверов.
– Непрерывный спам активационных ссылок на официальный email.
– Выполнение в течение 40-240 часов. Можем растянуть по времени сколько угодно.
– Прогон с запрещёнными ключами.
Telgrm: @exrumer
Skype: xrumer.pro
WhatsApp: +7(977)536-08-36
icq: 5688885
Только Эти!
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: https://ametathletics.sale
To your success,
Aleida
Hey, are you still in business? I used a tool to run a free website report and noticed a ton of major issues! If you want to see for yourself go to https://shineranker.com
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:
https://www.youtube.com/watch?v=NYCG0JEEhvQ
Kind Regards,
Cassie
Telephone: (888) 850-1556
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: https://fashiondaily.shop
To your success,
Noelia
Compartiendo codigo… – Programación y ejemplos de código
Добрый день!
Выполняем лучшие «убийственные» прогоны для сайтов конкурентов. Всего от 2000 руб.
– Гарантированный результат. Сайты конкурентов «упадут».
– Наибольшее число негативных фитбеков.
– Собрана специальная база – выжимка самых сильных площадок из 10 млн. интернет-ресурсов (порно, вирусных, спамных и т.д.). Это работает бесперебойно.
– Прогон делаем одновременно с четырех мощных серверов.
– Постоянный спам активационных ссылок на официальный e-mail.
– Можем растянуть как угодно по времени.
– Прогон с запретными ключевыми фразами.
Телегрм: @exrumer
Skype: xrumer.pro
WhatsApp: +7(977)536-08-36
icq: 5688885
Только Эти!
Horny Shriya called you 2 times. She is online. Click the below link to chat with her. She is very horny now.
https://live-sex-chat.club/
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: https://magicmat.biz
Thank You,
Sylvia
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 jasperbot.com it’s free to try as well.
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 muchocodigo.com 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: getlisted.directory/muchocodigo.com
Act today, and we will expedite your listings and waive the processing charge!
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: linterna.store
Regards,
Meridith
Horny Shriya called you 2 times. She is online. Click the below link to chat with her. She is very horny now.
https://live-sex-chat.club/