Php Regex在每个单词后面加引号,后跟冒号

Php Regex在每个单词后面加引号,后跟冒号,php,json,regex,object-literal,Php,Json,Regex,Object Literal,我想在每个表达定义的单词周围加引号。所有单词都必须以冒号结尾 例如: def1: "some explanation" def2: "other explanation" 必须转变为 "def1": "some explanation" "def2": "other explanation" 如何使用PHP中的preg_replace编写此代码 我有这个: preg_replace('/\b:/i', '"$0"', 'def1: "some explanation"') 但它只引用了冒号

我想在每个表达定义的单词周围加引号。所有单词都必须以冒号结尾

例如:

def1: "some explanation"
def2: "other explanation"
必须转变为

"def1": "some explanation"
"def2": "other explanation"
如何使用PHP中的preg_replace编写此代码

我有这个:

preg_replace('/\b:/i', '"$0"', 'def1: "some explanation"')
但它只引用了冒号,而不是单词:

key":" "value"

以下是解决方案:

preg_replace('/([^:]*):/i', '"$1" :', 'def1: "some explanation"');
我已将您的regexp替换为
[^:::]*
,这意味着除
之外的所有字符:
然后我使用
()
,它将是
$1
。 然后我用引号重写
$1
,并添加已删除的

编辑:在每一行上循环并应用preg_replace,这样就可以了


如果您的模式始终与示例中显示的相同,即3个字符和1个数字(即def1、def2、def3等),则可以使用以下模式:

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

"def1": "some explanation" "def2": "other explanation"
另一种可能有数字或字符的解决方案:

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

"def1": "some explanation" "def2": "other explanation" "def3": "other explanation" "defz": "other explanation"
对上述解决方案的解释:

\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).
) 

这两种解决方案都将替换所有发生的情况。

它只适用于一个条目,在同一行中添加更多条目,然后再次测试:),只需将其应用于每一行;)我同意,但你需要具体说明;)如果有人帮助你,别忘了把答案标为正确:)看我的答案,它可能会帮助你替换所有发生的事情