Find a Link in PHP String and convert it into a Hyperlink? - php

Find a Link in PHP String and convert it into a Hyperlink so it becomes Clickable and opens in New Tab.
PHP Code / String:
<?php echo $post_details['description']; ?>
Test Link:
http://www.test.com

use this library. it automatically detect link from the string and make it clickable. you don't need to create a link just add a string having a link. this library will detect it automatically.
http://soapbox.github.io/jQuery-linkify/

Use this example to solve your problem
<?php
function makeClickableLink($text) {
$text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9#:%_\+.~#?&//=]+)', '\\1', $text);
$text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9#:%_\+.~#?&//=]+)', '\\1\\2', $text);
$text = eregi_replace('([_\.0-9a-z-]+#([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})', '\\1', $text);
return $text;
}
// Usage
// Email address example
$text = "you#example.com";
echo makeClickableLink($text);
// URL example
$text = "http://www.example.com";
echo makeClickableLink($text);
// FTP URL example
$text = "ftp://ftp.example.com";
echo makeClickableLink($text);
?>

Related

Find all hyperlinks and add another redirect link within a text

I want to find all hyperlinks in text and adding a link redirect to every link
Example text
Hello Visit our website Here
The result I want is
Hello Visit our website Here
The code I have tried
$reg_exUrl = "/<a\s[^>]*href=(\\\" ??)([^\\\" >]*?)\\1[^>]*>(.*)<\/a>/siU";
$text = 'Hello visit our website Book';
if(preg_match($reg_exUrl, $text, $url)) {
echo preg_replace($reg_exUrl, ''.$url[2].'', $text);
} else {
echo $text;
}
So the result of my code is
Hello visit our website Book">https://example.com
Which in HTML inspect is
Hello visit our website Book">https://example.com</a>
$text = preg_replace_callback('#(<a[^>]+href=")([^"]+)(")#', 'add_track_callback', $text);
function add_track_callback($matches){
$track_url_base = 'https://mywebsite.com?q=';
return $matches[1] . $track_url_base . urlencode($matches[2]) . $matches[3];
}
Change $track_url_base as you need.
When there are no other attributes:
$string = preg_replace('~<a href="[^"]+">~', '<a href="#">', $string);
Otherwise:
$string = preg_replace('~<a ([^>]*)href="[^"]+"([^>]*)>~', '<a \\1href="#"\\2>', $string);
Demo:
php > $string = 'text....<a asd="blub" href="orig-link" title="bla"> Link text </a> other text .....';
php > echo preg_replace('~<a ([^>]*)href="[^"]+"([^>]*)>~', '<a \\1href="#"\\2>', $string); text....<a asd="blub" href="#" title="bla"> Link text </a> other text

Detect and Shorting long url text in php

I have long Text containg som html urls inside it from database .
im fetching it like that :
echo html_entity_decode($text);
and $text is like that in database:
$text = "this is my best <a href='http://www.website.com/andsoooooooooooom_biiiiiiiiiiiiiiiig_characters_heeeeeeeeere'>http://www.website.com/andsoooooooooooom_biiiiiiiiiiiiiiiig_characters_heeeeeeeeere</a> and some text here";
it echoes this :
this is my best http://www.website.com/andsoooooooooooom_biiiiiiiiiiiiiiiig_characters_heeeeeeeeere and some text here
But i want it display shorted text of the url and the href link is same like that :
this is my best http://www.website.com/andsoooooo... and some text here
How do i detect how long is it the link text and then short it automatically when fetching from database BUT the real link stayed as it is in href tag . thanks so much
EDIT im not looking to short the $text im looking to short the link inside the $text
Use substr():
$text = "this is my best <a href='http://www.website.com/andsoooooooooooom_biiiiiiiiiiiiiiiig_characters_heeeeeeeeere'>http://www.website.com/andsoooooooooooom_biiiiiiiiiiiiiiiig_characters_heeeeeeeeere</a>";
// Gets the whole tag
// e.g., "Text"
$linkTag = getTagFromYourUglyAssString($text, "a");
// Gets the tag's text value
// e.g., "Text"
$linkTagTextOnly = getTagTextFromYourUglyAssString($text, "a");
// Replace $linkTag with $linkTagTextOnly, whichever string you prefer ot shorten
$shortenedText = substr($linkTagTextOnly,0,10).'...';
echo $shortenedText;
function getTagFromYourUglyAssString($string, $tagname) {
$pattern = "/<$tagname ?.*>.*<\/$tagname>/";
preg_match($pattern, $string, $matches);
return array_merge($matches);
}
function getTagTextFromYourUglyAssString($string, $tagname) {
$pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
preg_match($pattern, $string, $matches);
return $matches[1];
}
EDIT: Actually, I think this is what you want:
$text = "this is my best <a href='http://www.website.com/andsoooooooooooom_biiiiiiiiiiiiiiiig_characters_heeeeeeeeere'>http://www.website.com/andsoooooooooooom_biiiiiiiiiiiiiiiig_characters_heeeeeeeeere</a>";
$shortenedLink = replaceTagTextFromYourUglyAssString($text, "a");
echo $shortenedLink;
// Should give:
// <a href="$text = "this is my best <a href='http://www.website.com/andsoooooooooooom_biiiiiiiiiiiiiiiig_characters_heeeeeeeeere">
// http://www.website.com/andsoooooooooooom_biiiiiiiiiiiiiiiig_chara...
// </a>
function replaceTagTextFromYourUglyAssString($string, $tagname) {
$pattern = "/(<$tagname ?.*>)(.*)(<\/$tagname>)/";
preg_match($pattern, $string, $matches);
if (count($matches) > 0) {
return $matches[0].substr($matches[1],0,10).'...'.$matches[2];
} else {
// do something else, 'cos no match found
}
}

PHP preg_replace multiple urls to links

I using this code to change urls to links:
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com http://www.ynet.co.il";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, ''.$url[0].'', $text);
} else {
// if no urls in the text just return the text
echo $text;
}
?>
But every link direct to the first link How can I make foreach that will solve it?
Thanks.
Haim
Try:
$reg_exUrl = "...";
$text = "...";
echo preg_replace($reg_exUrl, '$0', $text);
Much simpler ;)

PHP preg_replace multiple url replaces

Hey I am trying to do 2 preg_replace:
1.make all urls to html links
2.make all images url to html img tag
But these regexs cancel the other one
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$reg_exImg = "!http://[a-z0-9\-\.\/]+\.(?:jpe?g|png|gif)!Ui";
// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.comhttp://www.ynet.co.il http://dogsm.files.wordpress.com/2011/12/d7a1d7a7d795d791d799-d793d795.jpg";
// Check if there is a url in the text
$text = preg_replace($reg_exImg, '<img src=$0 >', $text);
$text = preg_replace($reg_exUrl, '$0', $text);
echo $text;
?>
How can I make that the preg_replace that make url to links dont do this to the tag?
Thanks.
Haim
This might be better as a callback.
Use just the $reg_exUrl, and do this:
$text = preg_replace_callback($reg_exUrl,function($m) {
if( preg_match("/\.(?:jpe?g|png|gif)$/i",$m[0])) {
return "<img src='".$m[0]."' />";
}
else {
return "<a href='".$m[0]."' rel='nofollow'>".$m[0]."</a>";
}
},$text);

Php link active

Well this is the function which active the link if someone put a link in message box with text.
My question is it doesn't show more than 1 link if someone put many link ex: www.yahoo.com www.gmail.com www.facebook.com, Then it's show only first link www.yahoo.com
function txt2link($text){
// force http: on www.
$text = ereg_replace( "www\.", "http://www.", $text );
// eliminate duplicates after force
$text = ereg_replace( "http://http://www\.", "http://www.", $text );
$text = ereg_replace( "https://http://www\.", "https://www.", $text );
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
$text = preg_replace($reg_exUrl, ''.$url[0].'', $text);
} // if no urls in the text just return the text
return ($text);
}
$url = "Alter pot waer it your pot http://css-tricks.com/snippets/php/find-urls-in-
text-make-links/ you may click the link www.yahoo.com or you may see what is the
http://www.youtube.com say, is it right?";
echo txt2link($url);
you can run this code to see the result.
Any Idea ?
This is one that someone here helped me build up a while back, I dunno where it is on stack anymore but I still use this function to date.. This handles many urls in one shot, with or without http: with or without www. in most cases, its true this could us a bit of refining, but in all does the job really nice.
//for finding URLs within body of text and converting them to a clickable link
//checks DNS to see if its valid and if the link HTML already exists ignores it.
function titleHyper($text){
$text = preg_replace( "/(www\.)/is", "http://", $text);
$text = str_replace(array("http://http://","http://https://"), "http://", $text);
$text = str_replace(array("<a href='", "<a href=\"", "</a>", "'>", "\">"), "", $text);
$reg_exUrl = "/(http|https|ftp|ftps|)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
preg_match_all($reg_exUrl, $text, $matches);
$usedPatterns = array();
$context = stream_context_create(array(
'http' => array(
'timeout' => 5
)
));
foreach($matches[0] as $pattern){
if(!array_key_exists($pattern, $usedPatterns)){
$usedPatterns[$pattern]=true;
$the_contents = #file_get_contents($pattern, 0, $context);
if(substr(trim($pattern), 0, 8) != "https://"){
$color = "#FF0000";
}
if (empty($the_contents)) {
$title = $pattern;
} else {
preg_match("/<title>(.*)<\/title>/Umis", $the_contents, $title);
$title = $title[1];
$color = "#00FF00";
//$title = htmlspecialchars($title, ENT_QUOTES); //saving data to database
}
$text = str_ireplace($pattern, "<a style='font-size: 14px; background-color: #FFFFFF; color: $color;' href='$pattern' rel='nofollow' TARGET='_blank'> $title </a>", $text);
}
}
return $text;
}
// titleHyper() in action example:
//$text = "Some sample text with WWW.AOL.com<br />http://www.youtube.com/watch?v=YaxKiZfQcX8 <br />Anyone use www.myspace.com? <br />Some people are nuts, look at this stargate link at http://www.youtube.com/watch?v=ZKoUm6z5SzU&feature=grec_index , like aliens exist or something. http://www.youtube.com/watch?v=sfN-7HczmOU&feature=grec_index and here's a secure site https://familyhistory.hhs.gov, unless you use curl or allow secure connections it will never get a title. <br /> This is a not valid site http://zzzzzzz and this is a dead site http://zwzwzwxzw.com.<br /> Lastly lets try an already made hyperlink and see what it does <a href='http://tacobell.com'>taco bell</a>";
//echo titleHyper($text);

Categories