简体   繁体   中英

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

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 )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM