PHP preg_replace multiple url replaces - php

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);

Related

Detect and convert url in link and detect image and convert to img PHP

Currently, I use this code to detect and convert URL in link in text.
But now, I need to keep this system, but detect and convert image too.
public function convert_to_link($text)
{
$reg_user = '!#(.+)(?:\s|$)!U';
if (preg_match_all($reg_user, $text, $matches))
{
return preg_replace($reg_user, '$0', $text);
}
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
if (preg_match("/\[img=([^\s'\"<>]+?)\]/i", $text))
{
//This is not working
return preg_replace("/\[img=([^\s'\"<>]+?)\]/i", "<img border=0 src=\"\\1\">", $text);
}
else
{
return preg_replace($reg_exUrl, '$0 ', $text);
}
}
else
{
return $text;
}
}
I use too [img][/img] code to convert image to but with the code located above, the result is bad :
Looks like your regex is looking for this format
[img=http://example.com/name.png]
but your example is in a different format
[img]http://example.com/name.png[/img]
a regex to identify the second form would be
"/^\[img\]([^\[]+)\[\/img\]$/i"

Parse image link into image HTML tag [duplicate]

What I want
If the URL in the string contains a .jpg at the end of the URL (not the string) then it should make an image from it with preg_replace else make a normal link.
so for example:
If I have http://www.example.com/images/photo.jpg then it should replace with:
<img src="http://www.example.com/images/photo.jpg" alt="http://www.example.com/images/photo.jpg">
The problem:
The URL is replaced with a link in any way and my regex isn't working :( .
What I have tried:
$content = preg_replace("/(http:\/\/[^\s]+(?=\.jpg))/i","<img src=\"$1\" alt = \"$1\"></img>",$content);
$content = nl2br(preg_replace("/(http:\/\/[^\s]+(?!\.jpg))/m", "$1", $content));
Try this
function replace_links($content)
{
if (preg_match('#(http://[^\s]+(?=\.(jpe?g|png|gif)))#i', $content))
{
$content = preg_replace('#(http://[^\s]+(?=\.(jpe?g|png|gif)))(\.(jpe?g|png|gif))#i', '<img src="$1.$2" alt="$1.$2" />', $content);
}
else
{
$content = preg_replace('#(http://[^\s]+(?!\.(jpe?g|png|gif)))#i', '$1', $content);
}
return $content;
}
$content = preg_replace('#\b(http://\S+\.jpg)\b#i', '<img src="$1" alt="$1" />', $content);
You don't need lookaround. Just go with
$content = preg_replace("#(http://[^ ]+\\.jpg(?= |$)#i","<img src=\"$1\" alt=\"$1\"/>", $content);
I think you used the lookahead operator when you wanted lookbehind. You could change (?=\.jpg) to (?<=\.jpg) but there are other, cleaner regex's I'm sure others will post.
This worked for me.
$parse_img='Hello, http://orbitco-ccna-pastquestions.com/images/Q5.jpg
In the figure above, router R1 has two point-to-point . ';
$parse_img=preg_replace('/(https?:\/\/(.\*)?\\.jpg|png|gif)[\s+]*/i',"< img src=\"$1\" alt = \"$1\">< /img >",$parse_img);
echo $parse_img;
Suyash

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 find all links in the text

I want to find all links in the text like this:
Test text http://hello.world Test text
http://google.com/file.jpg Test text https://hell.o.wor.ld/test?qwe=qwe Test text
test text http://test.test/test
I know i need to use preg_match_all, but have only idea in the head: start search from http|https|ftp and end search where space or end of the text appears, thats all i need really, so all links wiil be found properly.
Anyone can help me with php regexp pattern?
I think i need to use assertions in the end of pattern, but can`t understand their properly usage for now.
Any ideas? Thanx!
I'd go with something simple like ~[a-z]+://\S+~i
starts with protocol [a-z]+://
\S+ followed by one or more non-whitespaces where \S is a shorthand for [^ \t\r\n\f]
used modifier i (PCRE_CASELESS) (possibly not really necessery)
So it could look like this:
$pattern = '~[a-z]+://\S+~';
$str = 'Test text http://hello.world Test text
http://google.com/file.jpg Test text https://hell.o.wor.ld/test?qwe=qwe Test text
test text http://test.test/test';
if($num_found = preg_match_all($pattern, $str, $out))
{
echo "FOUND ".$num_found." LINKS:\n";
print_r($out[0]);
}
outputs:
FOUND 4 LINKS:
Array
(
[0] => http://hello.world
[1] => http://google.com/file.jpg
[2] => https://hell.o.wor.ld/test?qwe=qwe
[3] => http://test.test/test
)
Test on eval.in
function turnUrlIntoHyperlink($string){
//The Regular Expression filter
$reg_exUrl = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/";
// Check if there is a url in the text
if(preg_match_all($reg_exUrl, $string, $url)) {
// Loop through all matches
foreach($url[0] as $newLinks){
if(strstr( $newLinks, ":" ) === false){
$link = 'http://'.$newLinks;
}else{
$link = $newLinks;
}
// Create Search and Replace strings
$search = $newLinks;
$replace = ''.$link.'';
$string = str_replace($search, $replace, $string);
}
}
//Return result
return $string;
}
<?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";
// 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;
}
?>
Reference:http://css-tricks.com/snippets/php/find-urls-in-text-make-links/
Works like a charm. use this.
$str= "Test text http://hello.world";
preg_match_all('/\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&##\/%=~_|$?!:,.]*[A-Z0-9+&##\/%=~_|$]/i', $str, $result, PREG_PATTERN_ORDER);
print_r($result[0]);
The suggested answers are great, but one of them miss www. case, the other http://
So, let's combine all of those:
$text = Test text http://hello.world Test text
http://google.com/file.jpg Test text https://hell.o.wor.ld/test?qwe=qwe Test text
test text http://test.test/test
preg_match_all('/(((http|https|ftp|ftps)\:\/\/)|(www\.))[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\:[0-9]+)?(\/\S*)?/', $text, $results, PREG_PATTERN_ORDER);
print_r($results[0]);
The return value for PREG_PATTERN_ORDER will be Array of Arrays (results) so that $results[0] is an array of full pattern matches, $results[1] is an array of strings matched by the first parenthesized subpattern, and so on.
function turnUrlIntoHyperlink($string)
{
// 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, $string, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "<a target='_blank' href='{$url[0]}'>{$url[0]}</a>", $string);
} else {
// if no urls in the text just return the text
echo $string;
}
}
For converting URLs to tags, and recognizing URLs without http/https, try the below. It uses preg_replace_callback to avoid the issue in one of the other answers with the same URL appearing multiple times:
private function convertUrls($string) {
$url_pattern = '/(((http|https)\:\/\/)|(www\.))[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}(\:[0-9]+)?(\/\S*)?/';
return preg_replace_callback($url_pattern,
function($matches) {
$match = $matches[0];
if (strstr($match, ":") === false) {
$url = "https://$match";
} else {
$url = $match;
}
return '' . $url . '';
},
$string);
}
Alternative to regexp it´s use this library
Works very good, butnot for very complex codes.
foreach($html->find('a') as $element)
echo $element->href . '<br>';
And easy to use. No regular expressions skills required:-)
Not regexp, but finds it all and makes sure that they are not already encompassed in a tag already. It also checks to make sure that the link isn't encapsulated in (), [], "" or anything else with an open and close.
$txt = "Test text http://hello.world Test text
http://google.com/file.jpg Test text https://hell.o.wor.ld/test?qwe=qwe Test text
test text http://test.test/test I am already linked up
It was also done in 1927 (http://test.com/reference) Also check this out:http://test/index&t=27";
$holder = explode("http",$txt);
for($i = 1; $i < (count($holder));$i++) {
if (substr($holder[$i-1],-6) != 'href="') { // this means that the link is not alread in an a tag.
if (strpos($holder[$i]," ")!==false) //if the link is not the last item in the text block, stop at the first space
$href = substr($holder[$i],0,strpos($holder[$i]," "));
else //else it is the last item, take it
$href = $holder[$i];
if (ctype_punct(substr($holder[$i-1],strlen($holder[$i-1])-1)) && ctype_punct(substr($holder[$i],strlen($holder[$i])-1)))
$href = substr($href,0,-1); //if both the fron and back of the link are encapsulated in punctuation, truncate the link by one
$holder[$i] = implode("$href\" target=\"_blank\" class=\"link\">http$href</a>",explode($href,$holder[$i]));
$holder[$i-1] .= "<a href=\"";
}
}
$txt = implode("http",$holder);
echo $txt;
Output:
Test text http://hello.world Test text
http://google.com/file.jpg Test text https://hell.o.wor.ld/test?qwe=qwe Test text
test text http://test.test/test I am already linked up
It was also done in 1927 (http://test.com/reference) Also check this out:http://test/index&t=27
i use this function
<?php
function deteli($string){
$pos = strpos($string, 'http');
$spos = strpos($string, ' ', $pos);
$lst = $spos - $pos;
$bef = substr($string, 0, $pos);
$aft = substr($string, $spos);
if ($pos == true || $pos == 0) {
$link = substr($string, $pos, $lst);
$res = $bef . "<a href='" . $link . "' class='link' target='_blank'>link</a>" . $aft . "";
return $res;
}
else{
return $string;
}
}?>

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

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);
?>

Categories