PHP - Add link to a URL in a string - php

I have a function that will add the <a href> tag before a link and </a> after the link. However, it breaks for some webpages. How would you improve this function? Thanks!
function processString($s)
{
// check if there is a link
if(preg_match("/http:\/\//",$s))
{
print preg_match("/http:\/\//",$s);
$startUrl = stripos($s,"http://");
// if the link is in between text
if(stripos($s," ",$startUrl)){
$endUrl = stripos($s," ",$startUrl);
}
// if link is at the end of string
else {$endUrl = strlen($s);}
$beforeUrl = substr($s,0,$startUrl);
$url = substr($s,$startUrl,$endUrl-$startUrl);
$afterUrl = substr($s,$endUrl);
$newString = $beforeUrl."".$url."".$afterUrl;
return $newString;
}
return $s;
}

function processString($s) {
return preg_replace('/https?:\/\/[\w\-\.!~#?&=+\*\'"(),\/]+/','$0',$s);
}

It breaks for all URLs that contain "special" HTML characters. To be safe, pass the three string components through htmlspecialchars() before concatenating them together (unless you want to allow HTML outside the URL).

function processString($s){
return preg_replace('#((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)#', '$1', $s);
}
Found it here

Related

String to URL but detect if url is image?

i'm trying to do something in PHP
I'm trying to get the link of an image -> store it to my DB, but I'd like the user to be able to store text before it, and after it, I've gotten my hands on a similar function for links, but the image part is missing.
As you can see the turnUrlIntoHyperlink does a regex check over the entire arg passed, turning the text that contains it to the url, so users can post something like
Hey check this cool site "https://stackoverflow.com" its dope!
And the entire argument posting to my database.
However i can't seem to get the same function working for the Convert Image, as it simply won't post and removed text before/after it before when i made the attempt.
How would i do this in a correct way, and can i combine these 2 functions in to 1 function?
function convertImg($string) {
return preg_replace('/((https?):\/\/(\S*)\.(jpg|gif|png)(\?(\S*))?(?=\s|$|\pP))/i', '<img src="$1" />', $string);
}
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;
}
more explained in detail :
When i post a link like https://google.com/ I'd like it to be a href,
But if i post an image like https://image.shutterstock.com/image-photo/duck-on-white-background-260nw-1037486431.jpg , i'd like it to be a img src,
Currently, i'm storing it in my db and echoing it to a little debug panel,
Do you mean that you want to make an <img> inside <a> element?
Your turnUrlIntoHyperlink function have captured the url successfully, so we can just use explode to get string before and after the link.
$exploded = explode($link, $string);
$string_before = $exploded[0];
$string_after = $exploded[1];
Code example:
<?php
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)) {
// add http protocol if the url does not already contain it
$newLinks = $url[0][0];
if(strstr( $newLinks, ":" ) === false){
$link = 'http://'.$newLinks;
}else{
$link = $newLinks;
}
$exploded = explode($link, $string);
$string_before = $exploded[0];
$string_after = $exploded[1];
return $string_before.'<img src="'.$link.'">'.$string_after;
}
return $string;
}
echo turnUrlIntoHyperlink('Hey check this cool site https://stackoverflow.com/img/myimage.png its dope!');
Output:
Hey check this cool site <img src="https://stackoverflow.com/img/myimage.png"> its dope!
Edit: the question has been edited
Since an image URL is just another kind of link/URL, your logic should go like this pseudocode:
if link is image and link is url
print <img src=link> tag
else if link is url and link is not image
print <a href=link> tag
else
print link
So you can just write a new function to "merge" those two function:
function convertToImgOrHyperlink($string) {
$result = convertImg($string);
if($result != $string) return $result;
$result = turnUrlIntoHyperlink($string);
if($result != $string) return $result;
return $string;
}
echo convertToImgOrHyperlink('Hey check this cool site https://stackoverflow.com/img/myimage.png its dope!');
echo "\r\n\r\n";
echo convertToImgOrHyperlink('Hey check this cool site https://stackoverflow.com/ its dope!');
echo "\r\n\r\n";
Output:
Hey check this cool site <img src="https://stackoverflow.com/img/myimage.png" /> its dope!
Hey check this cool site https://stackoverflow.com/ its dope!
The basic idea is that since image url is also a link, such check must be done first. Then if it's effective (input and return is different), then do <img> convertion. Otherwise do <a> convertion.

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"

PHP Find & Replace where url and extension

I've been looking for an example on how to use preg_replace or RegEX to
search HTML for either http://www.mydomain.co.uk/page.html or /page.html
and replace .html with .app
I only want to replace the .html on pages that belong to this site
I have an app that uses pages from our website. When I link page from the app I put .app so it removes/ changes the formatting. Which works, I just want to dynamically edit the links on the pages.
Cheers
OK for those interested, I've cracked it.
It searches html for links then checks if the link belongs to site.
Find ".html" replace with ".app" within the link
Find old links replace with new links within html.
Thanks guys you pointed me in the right direction
function searchHTML($html){
// if the page is used by the app replace all domain pages .html with .app
$domain ='mydomain.com';
$regEX = '/<a[^>]+href=([\'"])(.+?)\1[^>]*>/I';
preg_match_all($regEX, $html, $match); //check page for links
for($l=0; $l<=count($match[2]); $l++){ //loop through links found
$link = $match[2][$l];//url within href
if ((strpos($link, $domain) !== false) || ($link[0]=="/")) { //check links are domain links(domain name or the first char is /)
$updateLink = str_replace(".html", ".app", $link);//replace .html ext with .app ext
$html = str_replace($link, $updateLink, $html); //update html with new links
}
}
return $html;
}
function changeURL($url) {
$url = str_replace('html', 'app', $url);
return $url;
}
echo changeURL('http://www.mydomain.co.uk/page.html');
Result: http://www.mydomain.co.uk/page.app
Try this, works with PHP 4 >= 4.0.5
<?php
$string = "http://www.mydomain.co.uk/page.html";
$string = preg_replace_callback("/mydomain.co.uk\/.+?(html)$/", "replace", $string);
function replace($matches) {
return str_replace("html", "app", $matches[0]);
}
echo $string;
<?php
// it's important to use the $ in regex to be sure to replace only the suffix and not a part of the url
function change_url($url, $find, $replace){
return preg_replace("#\\.".preg_quote($find, "#")."$#uim", ".".$replace, $url);
}
echo change_url("http://www.mydomain.co.uk/page.html", "html", "app");
//retuns http://www.mydomain.co.uk/page.app
?>

Apply inline CSS to PHP preg_replace or str_replace function

I have a PHP function that is calling the following:
function availability_filter_func($availability) {
$replacement = 'Out of Stock - Contact Us';
if(is_single(array(3186,3518)))
$availability['availability'] = str_ireplace('Out of stock', $replacement, $availability['availability']);
}
As you can see I am replacing the text string with custom text, however
I need the "Contact Us" text to be Contact Us - how would I go about doing this? Inputting raw html into the replacement string makes the html a part of the output.
Echo does not work and breaks the PHP function - same with trying to escape the PHP function, inserting html on on the entire string, and unescape the function.
Any advice would be appreciated, thank you.
Your code seems to be a complex way of doing this
function availability_filter_func($availability) {
$default = "Out of Stock";
$string = "<a href='mailto:contact#example.com'>Contact Us</a>";
if($availablity !== "") {
$return = $availability;
} else {
$return = $default;
}
return "$return - $string";
}
Try the Heredoc Syntax
$replacement = <<<LINK
Contact Us
LINK;

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

Categories