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 links after using the 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 = "";
$bitlink = "";
$pattern = '/[\'"](' . preg_quote($u, '/') . ')[\'"]/si';
preg_replace($pattern, $bitlink, $subject);