Reputation: 9529
I'm developping a simple cms and in some cases I want to store a paragraph in the database which may contain some links but I don't want to store html code in the database, I want it to be as follows:
some text, some text ||keyword||http://an-external-site.com/keyword|| some text and some text
and then use php to generate a link like this:
some text, some text <a href="http://an-external-site.com/keyword">keyword</a> some text and some text
So, how to do it? with preg_replace() for example
And is there a way to have the url point to an internal page within my site using a pre-defined variable, for example
some text, some text ||keyword||MS/keyword|| some text and some text
which will be:
some text, some text <a href="http://mysite.com/keyword">keyword</a> some text and some text
where MS refers to my site for example http://mysite.com/
So here the php function gets the pattern and then decides whether to simply use the full url as in the example 1 or to replace MS with the pre-defined variable which equals http://mysite.com/
Thanks.
Upvotes: 0
Views: 124
Reputation: 3882
I would recommend to use some class like bbcode to directly get non-html code in your project.
If you still want to use regexp you can use something like this:
$pattern = '=^(.*)<a(.*)href\="?(\S+)"([^>]*)>(.*)</a>(.*)$=msi';
while (preg_match($pattern, $row, $txt))
{
/* $txt[3] holds the link. */
echo $txt[3]."\n";
$row = $txt[1]." here was a link ".$txt[6];
}
/* print $row */
print "<br>".nl2br($row);
Upvotes: 1