-1
string = "(KEY)anything (KEY)anything (A)anything (KEY)anything";

result should be

string = "<p>anything</p> <p>anything</p> (A)anything <p>anything</p>";
faressoft
  • 17,177
  • 42
  • 96
  • 138

4 Answers4

2
$result = preg_replace('/\(KEY\)(\w+)/', '<p>\1</p>', $subject);

will work on your example.

If anything can be more than one word and is defined as "anything after (KEY) and before the next opening parenthesis", then you can use

$result = preg_replace('/\(KEY\)([^(]+)/', '<p>\1</p>', $subject);
Tim Pietzcker
  • 297,146
  • 54
  • 452
  • 522
1

Replace \(KEY\)(\w+) with <p>$1</p>, or whatever the equivalent php notation is.

This assumes that the boundaries are word boundaries (anything other than 0-9A-Za-z_).

Tim Pietzcker
  • 297,146
  • 54
  • 452
  • 522
OrangeDog
  • 30,151
  • 11
  • 105
  • 177
1

If you don't know how to start, here is an excellent tutorial on regular expressions:
Learning Regular Expressions

There are also nice (and free) tools to help you crafting them:
https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world

Community
  • 1
  • 1
mario
  • 138,064
  • 18
  • 223
  • 277
0

Check out preg_replace (http://php.net/manual/en/function.preg-replace.php)

$pattern = '\(KEY\)(\w+)\s';
$replacement = '<p>$1</p>';
$string = preg_replace($pattern,$replacement,$string);

Something like that should work.

nivshah
  • 41
  • 4