preg_replace 推特 url 无法使用问号 php

preg_replace twitter url not working with question mark php

我创建了下一个函数来用 div 替换 url 及其 id。

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

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

return $string;
  }

我用这种url

效果很好
 https://twitter.com/Minsa_Peru/status/1260658846143401984

但是当我使用这个 url

时它检索到一个例外 ?s=20
https://twitter.com/Minsa_Peru/status/1262730246668922885?s=20

如何删除此 ?s=20 文本,以便发挥我的作用?我所知道的是我需要改进我的正则表达式模式。谢谢。

如果您只需要正则表达式:

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

因为?不是数字,所以它将与 (.*) 分开,这意味着一切都休息,在这种情况下是 ?s=xyz,最后一个问号 ? 是说它可以存在或不存在。

Learn regex