Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php replace url in string with totally new url

Tags:

url

php

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.

like image 910
danyo Avatar asked Oct 14 '13 08:10

danyo


People also ask

How to replace url in PHP?

you can do : $url = 'http//:www.bobsplace.com/events/georgetown/12354544233123'; $my_var = 'foobar'; $url = str_replace("georgetown", $my_var, $url );

What is str_ replace in PHP?

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.

How to send in url PHP?

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 -_.


2 Answers

Can you just use PHP's str_replace() function? Something like

str_replace($url, $short_url, $text);
like image 145
natbooth Avatar answered Sep 18 '22 13:09

natbooth


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);
like image 23
2 revs, 2 users 95% Avatar answered Sep 20 '22 13:09

2 revs, 2 users 95%