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"
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.
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.