Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

345
Vistas
Regex to put quotes around every word followed by colon

I want to put quotes around every word expressing a definition. All words must do so by a trailing colon.

For example:

def1: "some explanation"
def2: "other explanation"

Must be transformed to

"def1": "some explanation"
"def2": "other explanation"

How do I write this with preg_replace in PHP ?

I have this:

preg_replace('/\b:/i', '"$0"', 'def1: "some explanation"')

But it only enquotes the colon, not the word:

key":" "value"
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Here is the solution :

preg_replace('/([^:]*):/i', '"$1" :', 'def1: "some explanation"');

I've replace your regexp by [^:]*, which means all caracter except : and then I get it by using (), which will be in $1. I then rewrite $1 with the quotes and add the : which had been removed.

Edit : Loop on each line and apply the preg_replace, and that will do the trick.

http://ideone.com/9qp8Hv

about 4 years ago · Santiago Trujillo Denunciar

0

If your pattern will be always like same as you show in example i.e. 3 character and 1 digit (i.e. def1, def2, def3 and so on) then you can use below pattern:

echo preg_replace('/\w+\d{1}/', '"$0"', 'def1: "some explanation" def2: "other explanation"');

output:

"def1": "some explanation" "def2": "other explanation"

Another solution which may have digit or character:

echo preg_replace('/\w+(?=:)/', '"$0"', 'def1: "some explanation" def2: "other explanation" def3: "other explanation" defz: "other explanation"');

Output:

"def1": "some explanation" "def2": "other explanation" "def3": "other explanation" "defz": "other explanation"

Explaination of above solution:

\w Word. Matches any word character (alphanumeric & underscore).
+ Plus. Match 1 or more of the preceding token.
(?= Positive lookahead. Matches a group after the main expression without including it in the result.
: Character. Matches a ":" character (char code 58).
) 

Both solution will replace all occurance.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda