PHP making clickable links - php

I have here a function that creates a clickable link:
function makeClickableLinks($text) {
$notIncludedonLink = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i', '', $text); // removing not included on the link
$urlLink = str_replace($notIncludedonLink,'',$text);
$finalText = str_replace($urlLink,''.$urlLink.'',$text);
return $finalText;
}
But instead of returning plain clickable link:
http://docs.google.com/
it displays:
http://docs.google.com/
I tried using htmlentities but it doesn't work.
Here's a JS code that sends data to server:
function checkNewLink() {
var latestId = $("input[name=latestLink]").val();
$('.newReply').load("links/ajax.php?action=newreply&msgid=<?php echo $msgId; ?>&latestid=" + latestId);
}
setInterval("checkNewLink()", 200);
where latestId contains the inputted link. It will be sent to ajax.php. Every 200 ms, it will check if there are new inputted link.

<?php
function makeClickableLinks($text){
return preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9#:%_+.~#?&;//=]+)!i', '$1', $text);
}
echo makeClickableLinks('test http://docs.google.com/ test');
output code (http://codepad.org/EZE1HFZ4)
test http://docs.google.com/ test
AFTER UPDATE
change
setInterval("checkNewLink()", 200);
to
setInterval(function(){ checkNewLink() }, 200);
read setInterval() Method

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.

Get dynamic content from HTML

I'm trying to capture the content of a div from an html page with this code:
$content = file_get_contents('http://player.rockfm.fm/');
$content = preg_replace("/\r\n+|\r+|\n+|\t+/i", " ", $content);
preg_match('/<div id=\"metadata_player\">(.*?)<\/div>/', $content , $matchs);
print_r($matchs);
The result is empty, because that code is generated by javascript or ajax.
Is there any other way than using https://github.com/neorai/php-webdriver?
Solution:
$result = file_get_contents("http://bo.cope.webtv.flumotion.com/api/active?format=json&podId=78");
$array_full=(json_decode($result, true));
$symbols = array('"','}','{');
$array_full['value'] = str_replace($symbols, "", $array_full['value']);
$array_author_title= explode(",", $array_full['value']);
$array_author = explode(":", $array_author_title[1]);
$array_title = explode(":", $array_author_title[2]);
echo "Author: ".$array_author[1];
echo "</br>Title: ".$array_title[1];
thanks to: #urban and How to use cURL to get jSON data and decode the data?
This page is loading weirdly (Seems like it is firing 3 loadFinished events! Anyhow, the following code works:
// "Normal" JS
function waitForMetadata() {
// Initialize global meta
var meta = page.evaluate(function() {
return document.getElementById("metadata_player")
});
var txt = meta.innerHTML;
console.log("meta: '" + meta.outerHTML + "'")
if (txt != "") {
phantom.exit(0);
} else {
setTimeout(waitForMetadata, 1000);
}
}
// PhantomJS
var page = require('webpage').create();
page.open('http://player.rockfm.fm/')
page.onLoadFinished = function(status) {
console.log("Status: " + status);
if(status !== "success") {
console.log("FAIL!")
phantom.exit(1);
}
waitForMetadata();
};
The first part is a function that checks the contents of the div and if it is empty it schedules itself, else prints and exits. The second part is straight out of phantomJS tutorial: declares a page, registers an onLoad function and loads it.
Example output:
urban#kde-2:/tmp$ phantomjs ./test.js
Status: success
meta: '<div id="metadata_player"></div>'
Status: success
meta: '<div id="metadata_player"></div>'
meta: '<div id="metadata_player"></div>'
meta: '<div id="metadata_player"></div>'
meta: '<div id="metadata_player"></div>'
meta: '<div id="metadata_player"></div>'
meta: '<div id="metadata_player"></div>'
meta: '<div id="metadata_player"></div>'
meta: '<div id="metadata_player">GUNS N' ROSES<br><span id="artist">KNOCKIN' ON HEAVEN'S DOOR</span></div>'
NOTE: Once the content is loaded, with JS you can do whatever you like (instead of printing). Also, I think you want to use the span id=artist later on...
UPDATE 1:
This made me stubborn... I could not make it with with phantomjs however, I inspected the ajax call this page makes and it seems that you can get the currently playing song with:
$ curl 'http://bo.cope.webtv.flumotion.com/api/active?format=json&podId=78'
{"id": null, "uuid": "DFLT", "value": "{\"image\": \"\", \"author\": \"AEROSMITH\", \"title\": \"AMAZING\"}"}
This means you can do use any language you like and json_decodetwice: (1) for the outer map having id, uuid and value and (2) decode the value. My only concern would be if podId changes... but is seems static.
Hope it helps

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"

Specified Text getting converted into icons while posting but doesnt do the same while receiving

I tried modifying a chat script.
(The original script is from Eliza Witkowska link.) I mainly tried converting some text into emoticons. So far I can only convert text into emoticons properly.
But, the text gets converted to icons only when I send the message but doesn't get converted when I receive the message on another browser (I'm using sessions so I have to use another browser) unless a refresh or I send a message from that another browser.
To be more clear, suppose I have logged in to an a/c from chrome and another a/c from Firefox; when I send a message from Chrome, the specified characters get converted into icons but only the characters show up on firefox until a page refresh or until a new message is sent from firefox.
db.php
function check_changes(){
$result = $this->db->query('SELECT counting FROM news WHERE id=1');
if($result = $result->fetch_object()){
return $result->counting;
}
return 0;
}
function get_news(){
if($result = $this->db->query('SELECT * FROM news WHERE id<>1 ORDER BY add_date DESC LIMIT 50')){
$return = '';
while($r = $result->fetch_object()){
$timing=explode(" ", $r->add_date);
$return .= $r->title;
$return .='<p>'.$timing[1].' on '.$timing[0].'</p><hr/> ';
//$return .= '<hr/>';
}
return $return;
}
}
profile.php
function parseSmiley($text){
//Smiley to image
$smileys=array('o:)'=>'angel.gif', ':3'=>'colonthree.gif', 'o.O'=>'confused.gif', ":'("=>'cry.gif', '3:)'=>'devil.gif', ':('=>'frown.gif', ':O'=>'gasp.gif', '8)'=>'glasses.gif', ':D'=>'grin.gif', ">:("=>'grumpy.gif', '<3'=>'heart.gif', '^_^'=>'kiki.gif', ':*'=>'kiss.gif', ':v'=>'pacman.gif', ':)'=>'smile.gif', '-_-'=>'squint.gif', '8|'=>'sunglasses.gif', ':p'=>'tongue.gif', ':/'=>'unsure.gif', '>:O'=>'upset.gif', ';)'=>'wink.gif');
//Now you need to find and replace
foreach($smileys as $smiley=>$img){
$smiley = preg_quote($smiley, '/');
$text = preg_replace( "#(?<=\s|^)(?:$smiley)((?=\s|$))?#i", '<img src="emotions-fb/'.$img.'">', $text);
}
//Now only return it
return $text;
}
$print= parseSmiley($db->get_news());
<div id="message_short" data-counter="<?php echo (int)$db->check_changes();?>">
<?php echo wordwrap($print, 25, "\n", true);?>
</div>
<div id="message_long" data-counter="<?php echo (int)$db->check_changes();?>">
<?php echo wordwrap($print, 35, "\n", true);?>
</div>
Be sure to wrap get_news() everywhere with parseSmiley().
As I can see from the link provided, there is a checker.php in which $db->get_news() should be replaced with parseSmiley($db->get_news())

PHP - Add link to a URL in a string

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

Categories