Skip to content
Advertisement

preg_replace twitter url not working with question mark php

I have created the next function to replace an url by a div with its id.

 function twitterIzer($string){
  $pattern = '~https?://twitter.com/.*?/status/(d+)~';

   $string = preg_replace($pattern, "<div class='tweet' id='tweet$1' tweetid='$1'></div>", $string);    

return $string;
  }

It works well when I use this type of url

 https://twitter.com/Minsa_Peru/status/1260658846143401984

but it retrieve an excedent ?s=20 when I use this url

https://twitter.com/Minsa_Peru/status/1262730246668922885?s=20

How can I remove this ?s=20 text, in order to make work my function ? Anything I know is I need to improve my regex pattern. thank you.

Advertisement

Answer

If you want just regex:

$pattern = '/https?://twitter.com/.*?/status/(d+)(.*)?/';

Because ? is not a digit so it will seperate with (.*), this mean every thing rest and in this case is ?s=xyz, last question mark ? is to say that is can exist or not.

Learn regex

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement