Regex put quotation marks around each word followed by a colon
I want to put quotes around every word that expresses a definition. All words must do this with a reverse colon.
For example:
def1: "some explanation"
def2: "other explanation"
Needs to be converted to
"def1": "some explanation"
"def2": "other explanation"
How do I write this with preg_replace in PHP?
I have it:
preg_replace('/\b:/i', '"$0"', 'def1: "some explanation"')
But it only introduces a colon, not a word:
key":" "value"
source to share
Here's the solution:
preg_replace('/([^:]*):/i', '"$1" :', 'def1: "some explanation"');
I am replacing your regex with [^:]*
which means all characters except :
and then I get it using ()
that will be in $1
. Then I rewrite $1
with quotes and add :
which has been removed.
Edit: Loop on each line and apply preg_replace and that will do the trick.
source to share
If your template will always be the same as you show in the example, for example 3 characters and 1 digit (i.e. def1, def2, def3, etc.), you can use the template below:
echo preg_replace('/\w+\d{1}/', '"$0"', 'def1: "some explanation" def2: "other explanation"');
output:
"def1": "some explanation" "def2": "other explanation"
Another solution, which can be digit or symbol:
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"
Explanation of the 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 solutions will replace all events.
source to share