David Untama
David Untama

Reputation: 592

Find a inner text between 2 symbols and replace inner text using regular expressions in php

I've been googling and trying to get this myself but I can't and only get a headache. I have this string:

"estamos en el registro {id} cuyo contenido es {contenido} por lo que veremos su {foto}"

I need replace the {value} with $value getting a string like this

"estamos en el registro $id cuyo contenido es $contenido por lo que veremos su $foto"

It is posibble using regular expressions in PHP

Thanks in advance for any answer

Upvotes: 1

Views: 262

Answers (2)

hwnd
hwnd

Reputation: 70732

Yes it is possible, you can use the preg_replace() function to perform this task.

If the curly braces are always balanced, you can use the following.

$text = preg_replace('/{(.*?)}/', '$$1', $text);

Working Demo

Upvotes: 2

zx81
zx81

Reputation: 41838

Do it like this:

$replaced = preg_replace('~{([^}]*)}~', '$$1', $yourstring);

On the demo, see the substitutions at the bottom.

  • { matches the opening brace
  • } matches the closing brace
  • In ([^}]*), the parentheses captures to Group 1 [^}]*... [^}] is a negative character class that means one char that is not a closing brace, and the * quantifier means zero or more times
  • $$1 replaces the match with a literal $ and the content of capture Group ($1)

Upvotes: 2

Related Questions