views:

56

answers:

3

What I'm trying to do is, replacing symbols that would be changed start the string then the last symbol that would close the string - changing both of them into a link then it will be stored into the database, it's something like Wikipedia.

I want to have something like this when someone types in the textarea:

"This woman was killed by [Tom Hanks] in 2002"

The [ and ] will be converted into a link with the Tom Hanks in the link href (which is directed by htaccess - I've done this already).

So, it should output something like this:

"This woman was killed by <a href=\"Tom Hanks\">Tom Hanks</a> in 2002"

The link location will always be the name of the wrapped text.

After that, it should be able to be stored into the database with the slashes.

+2  A: 
$result = preg_replace('/\[(.*?)\]/i', '<a href=\"$1\">$1</a>', $subject);
Rifat
This won't be able to handle multiple replacements in a single string since it's greedy. E.g.: `"abc [link1] cde [link2] efg"` will turn to `"abc <a href="link1] cde [link2">link1] cde [link</a> efg"`
Max Shawabkeh
yes, you were right. I've change it to lazy... Now it should work...
Rifat
+3  A: 

You can use:

$s = preg_replace('~\[(.*?)\]~is', '<a href="\1">\1</a>', $s);
Max Shawabkeh
+1  A: 

Note that you may want to prevent quote marks and tags in the URL which could result in unwanted HTML codes being output.

$result = preg_replace("/\[([^\"\'<>\[\]]+)\]/i", "<a href=\"$1\">$1</a>", $subject);

PP