I am pulling in HTML from a database and displaying it on a webpage using PHP. Lets just say that the people who will be putting in the HTML are not very experiences and will probably struggle with just creating things such as links. I need all the links to open in new pages (which I will do by adding target="_blank"
inside the <a>
tags. Now the question: what is the best way to do this?
As an example the following HTML in the database:
<a href="www.google.com">link</a>
Should be outpus as:
<a href="www.google.com" target="_blank">link</a>
I currently have this line to do what I want:
$text = preg_replace('/(<a.*?)>/', '$1 target="_blank">', $text);
But as I know from this answer and many others on SO, regex and HTML is not advised. Is there a better way? Using a HTML/XML parser, etc. seems over the top for such a simple operation.