I am currently working on a short url script to work with twitter.
Currently i am entering my desired tweet text into a textarea with a long url. So far i have the following which detects the url:
$regex = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
if ( preg_match( $regex, $text, $url ) ) { // $url is now the array of urls
echo $url[0];
}
When a tweet is entered it will look something like this:
hi here is our new product, check it out: www.mylongurl.com/this-is-a-very-long-url-and-needs-to-be-shorter
I am then generating some random characters to append on the end of a new url, so it will end up something like this: shorturl.com/ghs7sj.
When clicking, shorturl.com/ghs7sj it redirects you to www.mylongurl.com/this-is-aver-long-url-and-needs-to-be-shorter. This all works fine.
My question is the tweet text still contains the long url. Is there a way i can replace the long url with the short one? Do i need some new code? or can i adapt the above to also do this?
My desired outcome is this:
hi here is our new product, check it out: shorturl.com/ghs7sj
This is based on wordpress so all information is currently stored in the posts and post_meta tables. Just a note that there will only ever be 1 url in the tweet.
you can do : $url = 'http//:www.bobsplace.com/events/georgetown/12354544233123'; $my_var = 'foobar'; $url = str_replace("georgetown", $my_var, $url );
The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.
The urlencode() function is an inbuilt function in PHP which is used to encode the url. This function returns a string which consist all non-alphanumeric characters except -_.
Can you just use PHP's str_replace() function? Something like
str_replace($url, $short_url, $text);
You can do the replacement inside a callback function by using preg_replace_callback()
:
$regex = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$text = preg_replace_callback($regex, function($url) {
// do stuff with $url[0] here
return make_short_url($url[0]);
}, $text);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With