0

I want to write a function, which takes string1 as an input, grabs whatever the text is between two parameters, manipulates the grabbed string and then return the whole thing.

For example, let's say I have this: [Hi] my name [is] John.

I want to have this:

     <a href='Hi'>Hi</a> my name <a href='is'>is</a> John.
Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
qeroqazo
  • 771
  • 1
  • 7
  • 9

1 Answers1

0
preg_replace('/\[(.*?)\]/', '<a href="$1">$1</a>', $str);
Wouter J
  • 40,437
  • 15
  • 101
  • 111
  • Interesting game, who-ever finds a (rather trivial) input this fails for gets 5 internet points. – Benjamin Gruenbaum Mar 24 '13 at 18:12
  • @WouterJ, this worked as a charm. What if I wanted it to be [[$string]] rather than [$string]? – qeroqazo Mar 24 '13 at 18:25
  • then you change `\[` into `\[\[` and `\]` into `\]\]`. Or you put `[[` and `]]` into a variable and put that in the regex by using [the `.` operator](http://php.net/operators.string) and use [`preg_quote`](http://php.net/preg-quote) to automatically escape reserved characters – Wouter J Mar 24 '13 at 18:27
  • @WouterJ that worked really nice as well. One last question please, your answer will be much appreciated. What if I wanted it to be {{$string}} ? – qeroqazo Mar 24 '13 at 18:42
  • 1
    @user1726488 well, I just say that (read my comment again...) – Wouter J Mar 24 '13 at 18:44