2

I have regular expression that's is removing all url from a string but I want to change this and add exception for my site link.

$url = 'This is url for example to remove www.somewbsite.com but i want to skip removing this url www.mywebsite.com';  

$no_url = preg_replace("/(https|http|ftp)\:\/\/|([a-z0-9A-Z]+\.[a-z0-9A-Z]+\.[a-zA-Z]{2,4})|([a-z0-9A-Z]+\.[a-zA-Z]{2,4})|\?([a-zA-Z0-9]+[\&\=\#a-z]+)/i", "★", $url);
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
R3aSoN
  • 23
  • 3

1 Answers1

0

First of all, since you are replacing with a hard-coded symbol, and you are using a case-insensitive modifier, your regex can be reduced to

'~(?:https?|ftp)://|(?:[a-z0-9]+\.)?[a-z0-9]+\.[a-z]{2,4}|\?[a-z0-9]+[&=#a-z]+~i'

whatever it means to match. Note that 2 alternatives here were too similar ([a-z0-9A-Z]+\.[a-z0-9A-Z]+\.[a-zA-Z]{2,4})|([a-z0-9A-Z]+\.[a-zA-Z]{2,4}), they are merged into 1 with the help of an optional non-capturing group ((?:[a-z0-9]+\.)?).

Now, if you want to avoid matching a specific pattern, you may use a SKIP-FAIL technique: match what you want to preserve and skip it.

'~www\.mywebsite\.com(*SKIP)(*FAIL)|(?:https?|ftp)://|(?:[a-z0-9]+\.)?[a-z0-9]+\.[a-z]{2,4}|\?[a-z0-9]+[&=#a-z]+~i'

See this regex demo.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563