0

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
  • string_replace [ for < a href=\" and ] for \"> no regex Commented Feb 11, 2010 at 13:21
  • that would not create the link... Commented Feb 11, 2010 at 13:30

3 Answers 3

3

You can use:

$s = preg_replace('~\[(.*?)\]~is', '<a href="\1">\1</a>', $s);
Sign up to request clarification or add additional context in comments.

Comments

2
$result = preg_replace('/\[(.*?)\]/i', '<a href=\"$1\">$1</a>', $subject);

1 Comment

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"
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.