تبدیل URL به لینک در نوشته با PHP
URL به لینک در نوشته با PHP – یکی از نمونه هایی که می توان به آن اشاره کرده لینک دهی کاربران در نظرات است
که به صورت خودکار به تگ a جهت دادن لینک تبدیل می شود .
با استفاده از تابع preg_match_all این امکان را فراهم می کنیم که بتوانیم با Regex قسمتی هایی که دارای URL می باشند را به تگ a تبدیل کنیم .
اسکریپت تبدیل رشته به URL
<?php function generateLinkFromStr($text){ $pattern = '/https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,}/mi'; preg_match_all($pattern , $text , $res); if(isset($res[0])) $res = end($res); return $res; } $text = "hello friends 2 you @#$- 5454 https://rapidcode.ir/topics/learn-programming/learn-php/ http://foxwp.ir/ aryawp.com"; $res = generateLinkFromStr($text); echo "without Link : {$text}<br><br>"; /* without Link : hello friends 2 you @#$- 5454 https://rapidcode.ir/topics/learn-programming/learn-php/ http://foxwp.ir/ aryawp.com<br><br> */ foreach($res as $link){ $text = str_replace($link , "<a target=\"_blank\" href=\"{$link}\">{$link}</a>", $text); } echo "With Link : {$text}<br><br>"; /* With Link : hello friends 2 you @#$- 5454 <a target="_blank" href="https://rapidcode.ir/topics/learn-programming/learn-php/">https://rapidcode.ir/topics/learn-programming/learn-php/</a> <a target="_blank" href="http://foxwp.ir/">http://foxwp.ir/</a> aryawp.com<br><br> */ ?>
ارسال نظر