Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

352
Views
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"
over 4 years ago · Santiago Trujillo
2 answers
Answer question

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

over 4 years ago · Santiago Trujillo Report

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!