0

I am currently inserting some body text into the DB. This is just plain text, but the users are also wanting to be able to add working links. To save making mass changes I am doing these changes be using a pop up that will insert their link in the following format:

[a]http://www.google.com[/a]

Each body text can have more than one link in.

When this is displayed on the relevant webpage the links will change to a standard html format:

<a href="http://google.com">http://www.google.com</a>

I can't seem to be able to setup a preg_match to get this to do this multiple times in a string (see example below):

hello world [a]http://google.com[/a] how are you?
Ok. [a]http://yahoo.com[/a] Thanks for asing. [a]http://bing.com[/a]

Any help would greatly be appreciated!!!

Thanks, Kane

3
  • Do you have an attempt? Commented Feb 19, 2015 at 15:53
  • Yeah I used this one... code/[a](.*)[/a]/code But it would return the following: code1 => google.com[/a] how are you? Ok. [a]yahoo.com[/a] Thanks for asing. [a]bing.comcode So it was only getting the outside "[a]" and "[/a]" Commented Feb 19, 2015 at 15:54
  • Sorry It's not very easy to read. /[a](.*)[/a]/ Commented Feb 19, 2015 at 15:58

2 Answers 2

1

Use this:

$str = "[a]http://www.google.com[/a] xy [a]http://www.google.com[/a]";
$str = preg_replace("/\[a\](.*)\[\/a\]/Usi", "<a href=\"\\1\">\\1</a>", $str);
echo $str;

Output:

<a href="http://www.google.com">http://​www.google.com</a> xy <a href="http://www.google.com">http://​www.google.com</a>;
Sign up to request clarification or add additional context in comments.

Comments

0

This should work:

$str = preg_replace('~\[a](.*?)\[/a]~si', "<a href='$1'>$1</a>", $str);

1 Comment

You have escaped the wrong square bracket: [ needs to be escaped, ] don't need.

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.