-1

I have this regex for preg_replace. He is replace all urls in given string.

Now I need replace only t.co urls. https://t.co/* and etc.

preg_replace('/\b((https?|ftp|file):\/\/|www\.)[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', ' ', $text);

How to do it with preg_replace?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Nijo
  • 31
  • 5
  • Will this work? `\bhttps?:\/\/t.co\S*` – Bren Jul 11 '20 at 06:42
  • 1
    Does this answer your question? [javascript Reg Exp to match specific domain name](https://stackoverflow.com/questions/32730133/javascript-reg-exp-to-match-specific-domain-name) – Bren Jul 11 '20 at 06:46

2 Answers2

1

You could use preg_replace and matching the specific urls only:

\bhttps?://t\.co/\S*

Explanation

  • \b Word boundary
  • https?:// Match the protocol with optional s and ://
  • t\.co Match t.co
  • /\S* Match / and 0+ non whitespace chars

Regex demo

Example code

preg_replace('~\bhttps?://t\.co/\S*~i', ' ', $text);
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

Probably not the most efficient solution, but you might give preg_replace_callback() a try.

For example:

preg_replace_callback('/\b((https?|ftp|file):\/\/|www\.)[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', function ($matches) {
    $url = $matches[0];
    if (preg_match('/^((https?:)?\/\/)?(www\.)?t\.co\b/i', $url)) {
        return ' ';
    } else {
        return $url;
    }
}, $text);
Gras Double
  • 15,901
  • 8
  • 56
  • 54