Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

344
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda