Using special, regular expression characters in regular expressions require you to escape them in the regular expression pattern.

I had an issue with dynamically getting an array of URLs from HREF attribute from links using PHP preg_match_all and then wanted to replace this array of URLs dynamically in a loop again with their Bit.ly links after using the Bit.ly API. Dynamically inserting a URL into a regular expression pattern doesn’t work but there is a way to make it work. Simply use preg_quote with a special, conditional delimiter.

Here is the code:

$u = "http://domain.com/path/to/file/";
$bitlink = "http://bit.ly/xYkswW";
$pattern = '/[\'"](' . preg_quote($u, '/') . ')[\'"]/si';
preg_replace($pattern, $bitlink, $subject);