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,753
  • 72
  • 57
  • 129
mechanical-turk
  • 801
  • 1
  • 8
  • 9

1 Answers1

0
preg_replace('/\[(.*?)\]/', '<a href="$1">$1</a>', $str);
Wouter J
  • 41,455
  • 15
  • 107
  • 112
  • 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]? – mechanical-turk 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}} ? – mechanical-turk 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