i have an array like this:
$array = array('domain1.com','domain2.net','domain3.org');
any way to replace only these domains into links with preg_replace?
currently have this little function, but parses all the domains:
function insert_referer($text){
$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
$ret = ' ' . $text;
$ret = preg_replace("#(^|[
])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret);
$ret = preg_replace("#(^|[
])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret);
$ret = substr($ret, 1);
return $ret;
}
This code does what you wanted:
$array = array('domain1.com','domain2.net','domain3.org'); $text = 'Some text including domain1.com/something and http://domain3.org'; echo preg_replace('/((?:https?:\/\/)?(?:' . implode('|', $array) . ')[-a-zA-Z0-9\._~:\/?#\[\]@\!\$&\'\(\)\*\+,;=]*)/', '\1', $text); // Outputs: // "Some text including <a href="domain1.com/something">domain1.com/something</a> and <a href="http://domain3.org">http://domain3.org</a>"
I didn't test the code itself so it may (I don't think it would but it's possible) contain typos, but I tested the regexp itself and it works perfectly.