Search code examples
phphtmltwitterpreg-replacestatus

preg replace twitter status and http or https PHP


I'll start with what I have:

// embed tweet
$embed_tweet =  '
  <blockquote class="twitter-tweet" data-cards="hidden" data-lang="en">
    <a href="https://twitter.com/\\4"></a>
  </blockquote>
';

$this->post['message'] = preg_replace('#(<a href="http://twitter.com)?/(status/([-|~_0-9A-Za-z]+)|v\/([-|~_0-9A-Za-z]+)&?.*?)">(http://twitter.com)?/(status/([-|~_0-9A-Za-z]+)|v\/([-|~_0-9A-Za-z]+)&?.*?)<\/a>#i', $embed_tweet, $this->post['message']);

// embed vine
$embed_player =  '<iframe src="https://vine.co/v/\\4/embed/simple" width="480" height="480" frameborder="0"></iframe>';

$this->post['message'] = preg_replace('#(<a href="http://vine.co)?/(embed/([-|~_0-9A-Za-z]+)|v\/([-|~_0-9A-Za-z]+)&?.*?)">(http://vine.co)?/(embed/([-|~_0-9A-Za-z]+)|v\/([-|~_0-9A-Za-z]+)&?.*?)<\/a>#i', $embed_player, $this->post['message']);

I am trying to make it so when a user posts a link to a Twitter status or a Vine post it auto embeds the post.

The Vine code was given to me and I managed to update parts of it and get it working only if its http or I added the s I can only make it one way or the other, I tried working from it to get the Twitter one to function.

But I have no idea hot to figure out the proper preg_replace for the Twitter embed.

A Twitter status link is as follows:

https://twitter.com/DrCustUmz/status/726561400617840641

So if a user posts that link like that and the post is submitted, it turns into:

<a href="https://twitter.com/DrCustUmz/status/726561400617840641" taget="_blank">https://twitter.com/DrCustUmz/status/726561400617840641</a>

So how can I achieve this, and how do I go about getting what I need for a preg_replace?

Also... What does that \\4 do exactly in the line

$embed_player =  '<iframe src="https://vine.co/v/\\4/embed/simple"...

Solution

  • Went on the learning more journey and this is what I came up with.

    // embed tweet
    $drc_embed_tweet =  '
      <blockquote align="center" class="twitter-tweet" data-cards="hidden" data-lang="en">
        <a href="https://twitter.com/\2/status/\3"></a>
      </blockquote>
    ';
    $this->post['message'] = preg_replace('~(<a href="https?://twitter.com)/(.*)/status/(.*)">(https?://twitter.com)/(.*)<\/a>~', $drc_embed_tweet, $this->post['message']);
    
    // embed vine
    
    $drc_embed_vine =  '<iframe align="center" src="https://vine.co/v/\2" width="480" height="480" frameborder="0"></iframe>';
    
    $this->post['message'] = preg_replace('~(<a href="https?://vine.co)/v/(.*)">(https?://vine.co)/v/(.*)<\/a>~', $drc_embed_vine, $this->post['message']);
    

    As for the numbers \4 From my understanding that is the portion of the reg. ex. being replace since the second reg. ex. \2 is the same thing either number can be used.