6

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.

2

2 Answers 2

6

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

str_replace($url, $short_url, $text);
Sign up to request clarification or add additional context in comments.

1 Comment

$url[0] to be precise.
4

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

1 Comment

This can be the right answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.