Need to have http added if not present before www - php

My function gets all the facebook description text from our string $FBdescription. This preg_replace does everything I need except when it finds a url like www.myurl.com in the description it places that in the href= and because it does not contain the http:// at the begining it of course causes problems when you click the link. How can this be adjusted to append the http:// if it's not there.
function fts_facebook_tag_filter($FBdescription)
//Converts URLs to Links in our Description Text
$FBdescription = preg_replace('#(?!(?!.*?<a)[^<]*<\/a>)(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-‌​Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]#i', '\0', $FBdescription);
return $FBdescription;
}

Not best but working solution: (prepends http:// if missing, inside href attribute only)
$FBdescription = 'BZRK Records and BZRK Black label Artists playing here More info : www.bzrk.agency https://www.facebook.com/daphne.merks/posts/988562257858538';
//Converts URLs to Links
$FBdescription = preg_replace('#(?!(?!.*?<a)[^<]*<\/a>)(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-‌​Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]#i', '\0', $FBdescription);
$splitano = explode("www", $FBdescription);
$count = count($splitano);
$returnValue = "";
for($i=0; $i<$count; $i++) {
if (substr($splitano[$i], -6, 5) == "href=") {
$returnValue .= $splitano[$i] . "http://www";
}
else if($i < $count - 1){
$returnValue .= $splitano[$i] . "www";
}
else {
$returnValue .= $splitano[$i];
}
}
echo $returnValue;

Related

Show In article ads every x amount of words repeatedly?

I have a code that shows in-article ads after a specified amount of words, the thing is:
If I write a very long article, the ad will be lost due to text length, so there will be only text showing. What I need to do is to create 1 or 2 ads and make it/them repeat indefinitely every 4 paragraphs and 250 words (just an example), based on article length.
HERE'S AN EXAMPLE:
This blog has the very same thing that I'm trying to achieve. As you scroll the article, you'll see that more and more ads will be loaded between the article paragraphs.
THIS IS MY CURRENT CODE:
// Insert ads after a number of words and after the </p> closing tag.
// https://stackoverflow.com/questions/42801541/insert-text-in-content-after-300-words-but-after-closing-tag-of-a-paragraph
function anunciamentosegundo($content) {
$ad_code = '<script type="application/javascript">Adsense code goes here</script>';
// only inject google ads if post is longer than 800 characters
$enable_length1 = 1800;
// Insert at the end of the paragraph every 200 words
$after_word1 = 400;
// Maximum of 2 ads
$max_ads = 2;
if (strlen($content) > $enable_length1) {
$len = strlen($content);
$i=0;
// Keep adding untill end of content or $max_ads number of ads has ben inserted
while($i<$len && $max_ads-->0) {
// Work our way untill the apropriate length
$word_cout = 0;
$in_tag = false;
while(++$i < $len && $word_cout < $after_word1) {
if(!$in_tag && ctype_space($content[$i])) {
// Whitespace
$word_cout++;
}
else if(!$in_tag && $content[$i] == '<') {
// Begin tag
$in_tag = true;
$word_cout++;
}
else if($in_tag && $content[$i] == '>') {
// End tag
$in_tag = false;
}
}
// Find the next '</p>'
$i = strpos($content, "</p>", $i);
if($i === false) {
// No more paragraph endings
break;
}
else {
// Add the length of </p>
$i += 4;
// Get ad as string
ob_start();
echo $ad_code ; //would normally get printed to the screen/output to browser
$ad = ob_get_contents();
ob_end_clean();
$content = substr($content, 0, $i) . $ad . substr($content, $i);
// Set the correct i
$i+= strlen($ad);
}
}
}
return $content;
}
add_filter( 'the_content', 'anunciamentosegundo' );
Currently I can show ads after an amount of words and paragraphs, but not every x amount words and paragraphs. What should I do?

Invalid html returned when "www" or ".com" comes along url for a link which is created dynamically using regular expression in PHP

I am getting invalid html as out when i try to create link dynamically using regular expression using a pattern.
This is my function which creates link:
$message ="sddsdsd ##[Sanesh Sunny:ZGNjBQN9ac3K] dsdsdsd ";
function convert_usertags_links($message,$extraParams){
$tag_name = 'a'; //default a
$has_link = $new_tab = 0; //default no link
$href = $target = $sel_id = $tag_col = "";
$tag_col = 'tag_col';
if(isset($extraParams['tag_name']) && $extraParams['tag_name']!="")
$tag_name = $extraParams['tag_name'];
if(isset($extraParams['tag_col']) && $extraParams['tag_col']!="")
$tag_col = $extraParams['tag_col'];
if(isset($extraParams['has_link']) && $extraParams['has_link']!="")
$has_link = $extraParams['has_link'];
if(isset($extraParams['new_tab']) && $extraParams['new_tab']!="")
$new_tab = $extraParams['new_tab'];
if(isset($extraParams['selector_id']) && $extraParams['selector_id']!="")
$sel_id = $extraParams['selector_id'];
$site_url = 'www.google.com/project/';
if($has_link == 1)
$href = " href='".$site_url."user/profile/$2' ";
if($has_link == 1)
$target = " target='_blank' ";
/*
* to match numbers only
*/
$pattern = "/##\[([^:]*):(.*?)\]/";
#$pattern = "/##\[([^:]*):([0-9a-zA-Z]*)\]/";
$matches = array();
preg_match_all($pattern, $message, $matches);
$output = preg_replace($pattern, "<".$tag_name." class='".$tag_col."' id='".$sel_id."_$2'".$href.$target." >$1</".$tag_name.">", $message);
return $output;
}
This functions works perfect in localhost but when i tried the same in my stagging server having site_url like "https://dsdsdsdsdsd.com/project" i am getting invalid html like:
<a class="tag_col" id="user_tag_link_ZGV3ZmZ9ac3K_ZGNjBQN9ac3K" href="<a href="www.google.com/4thambit-v6/user/profile/ZGNjBQN9ac3K" target="_blank">www.google.com/4thambit-v6/user/profile/ZGNjBQN9ac3K</a>" target="_blank">Sanesh Sunny</a>
The href contains another a tag inside... if i pass site_url as 192.168.1.X which is IP Adresss it is working fine but when i use "www" or ".com" inside sit_url the above invalid html is returned with another a tag inside href......
Any idea why this happening ? i tried few sites but no help....

Auto-link in a string not working for short link

I need a form to autolink links that users input in text fields. I found an example on stack which works perfectly, except for one thing. if the user inputs a link without including http:// or https:// and instead starts the link only using www. the link does not work properly.
ie a user input would be
check out our twitter!
www.twitter.com/#!/profile
and our facebook!
https://www.facebook.com/profile
the output would be
check out our twitter!
www.twitter.com/#!/profile
and our facebook!
http://www.facebook.com/profile
so the facebook link works perfectly, but the twitter one would not, as its being linked to the current location the user is on plus the new link, ie if they are currently on www.example.com the link would become www.example.com/www.twitter.com/#!/profile
for the life of me, i cant figure out how to fix this by simply adding http:// to the beginning of the link, this is the function:
function auto_link_text($text) {
$pattern = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
return preg_replace_callback($pattern, 'auto_link_text_callback', $text);
}
function auto_link_text_callback($matches) {
$max_url_length = 50;
$max_depth_if_over_length = 2;
$ellipsis = '…';
$url_full = $matches[0];
$url_short = '';
if (strlen($url_full) > $max_url_length) {
$parts = parse_url($url_full);
$url_short = $parts['scheme'] . '://' . preg_replace('/^www\./', '', $parts['host']) . '/';
$path_components = explode('/', trim($parts['path'], '/'));
foreach ($path_components as $dir) {
$url_string_components[] = $dir . '/';
}
if (!empty($parts['query'])) {
$url_string_components[] = '?' . $parts['query'];
}
if (!empty($parts['fragment'])) {
$url_string_components[] = '#' . $parts['fragment'];
}
for ($k = 0; $k < count($url_string_components); $k++) {
$curr_component = $url_string_components[$k];
if ($k >= $max_depth_if_over_length || strlen($url_short) + strlen($curr_component) > $max_url_length) {
if ($k == 0 && strlen($url_short) < $max_url_length) {
// Always show a portion of first directory
$url_short .= substr($curr_component, 0, $max_url_length - strlen($url_short));
}
$url_short .= $ellipsis;
break;
}
$url_short .= $curr_component;
}
} else {
$url_short = $url_full;
}
return "<a rel=\"nofollow\" href=\"$url_full\">$url_short</a>";
}
Use strpos function.
if the input contains "http://" forward directly. Otherwise add it direct it.

How to echo few lines only from a row named body saved in mysql?

Basically I want to echo only summary of my blog post on a certain page by making a function() that must limit the number of counts of words as specified there.
function sumarize($your_string){
$count++;
$maximum = 10;
foreach(explode("\n", $your_string) as $line){
$count++;
echo $line."\n";
if ($count == $maximum) break;
}
}
Lets say your table (named main) looks like that.
id | blogpost
1 sample1
2 sample2
...
At first you need to connect to db
$db=NEW MYSQLI('localhost', 'username', 'pass', 'dbname') or die ($db->error);
Then write following piece of code
function sumarize($your_string){
$count++;
$maximum = 10;
foreach(explode("\n", $your_string) as $line){
$count++;
echo $line."\n";
if ($count == $maximum) break;
}
}
$result=$db->query("SELECT `id`, `blogpost` FROM `main`");
while($row->fetch_object()){
echo sumarize($row->blogpost);
}
This is how to get work genesis φ's solution
this one takes into account numbers of character whilst ending at the last word without cutting out a character
use
select .... SUBSTR(body,1,300) .....
later you can use this function in php to cut the string at the last space or period so you wont get a half cut word in the end. The second parameter is the number of characters you want.
function shorten_string($string, $characters)
{
$shortened_string = "";
$smaller_string = substr($string, 0, $characters);
$pos_of_last_space = strrpos($smaller_string, " ");
$pos_of_last_break = strrpos($smaller_string, " ");
if (strlen($string) <= $characters) {
$shortened_string = $string;
} elseif (!$pos_of_last_space && !$pos_of_last_break) {
$shortened_string = $smaller_string;
} else {
$break_at = 0;
if ($pos_of_last_space > $pos_of_last_break) {
$break_at = $pos_of_last_space;
} else {
$break_at = $pos_of_last_break;
}
$shortened_string = substr($smaller_string, 0, $break_at);
}
}
NOTE: takes care of spaces put in html with 'nbsp'
Save the summary and body of your blog posts in different columns.

Always returning 0, Google SERP Checker

My function searches google for the specific keyword and then checks for the site and then returns the what position it is on google (its for my seo dashboard) but it always return's 0, hopefully some fresh eyes can find the faults
<?php
function GoogleSerp($searchquery, $searchurl){
if(!empty($searchquery) && !empty($searchurl))
{
$query = str_replace(" ","+",$searchquery);
$query = str_replace("%26","&",$query);
// How many results to search through.
$total_to_search = 50;
// The number of hits per page.
$hits_per_page = 10;
// Obviously, the total pages / queries we will be doing is
// $total_to_search / $hits_per_page
// This will be our rank
$position = 0;
// This is the rank minus the duplicates
$real_position = 0;
$found = NULL;
$lastURL = NULL;
for($i=0;$i<$total_to_search && empty($found);$i+=$hits_per_page)
{
// Open the search page.
// We are filling in certain variables -
// $query,$hits_per_page and $start.
// $filename = "http://www.google.co.uk/xhtml?q=$query&start=$i&sa=N";
$filename = "http://www.google.co.uk/m?q=$query&num=$hits_per_page&filter=0&start=$i&sa=N";
$file = fopen($filename, "r");
if (!$file)
{
return "error";
}
else
{
// Now load the file into a variable line at a time
while (!feof($file))
{
$var = fgets($file, 1024);
// Try and find the font tag google uses to show the site URL
if(eregi("<span class=\"c\">(.*)</span>",$var,$out))
{
// If we find it take out any <B> </B> tags - google does
// highlight search terms within URLS
$out[1] = strtolower(strip_tags($out[1]));
// Get the domain name by looking for the first /
$x = strpos($out[1],"/");
// and get the URL
$url = substr($out[1],0,$x);
$url = str_replace("/","",$url);
$position++;
// If you want to see the hits, set $trace to something
// if($trace)return($url."<br>");
// If the last result process is the same as this one, it
// is a nest or internal domain result, so don't count it
// on $real_position
if(strcmp($lastURL,$url)<>0)$real_position++;
$lastURL = $url;
// Else if the sites match we have found it!!!
if(strcmp($searchurl,$url)==0)
{
$found = $position;
// We quit out, we don't need to go any further.
break;
}
}
}
}
fclose($file);
}
if($found)
{
$result = $real_position;
}else{
$result = 0;
}
}
return $result;
}
?>
Try urlencode() instead of the two replaces on the query.

Categories