I have a textarea which uses CKEditor to generate HTML. I want to ensure that all links the user enters have their target="_blank"
. I thought I'd need to do two regex checks: one to replace any target="..."
to target="_blank"
, and another to just insert target attribute where target attribute doesn't exist. I'm not making much progress:
// where target attribute doesn't exist, add it
preg_replace("/<a(\s*(?!target)([\w\-])+=([\\"\'])[^\\"\']+\3)*\s*\/?>/", "<a target="_blank"$1>", $input_lines);
This works in this simple case:
<a href="#">one</a> ---> <a target="_blank" href="#">one</a>
It does not work for <a href="#" alt="hello">one</a>
, I'm not sure why but then I don't normally do things this challenging with regular expressions.
Also, how would I replace existing target="..."
(e.g. target="_parent
") with strictly target="_blank
"?