【问题标题】:Regex to put quotes around every word followed by colon正则表达式在每个单词周围加上引号,后跟冒号
【发布时间】:2017-08-29 08:08:28
【问题描述】:

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

例如:

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"

【问题讨论】:

  • 如果有人帮助你,别忘了将答案标记为正确 :)
  • 查看我的回答,它可能会帮助您替换所有出现的情况

标签: php json regex object-literal


【解决方案1】:

解决办法如下:

preg_replace('/([^:]*):/i', '"$1" :', 'def1: "some explanation"');

我已将您的正则表达式替换为[^:]*,这意味着除: 之外的所有字符 然后我通过使用() 得到它,它将在$1 中。 然后我用引号重写$1 并添加已删除的:

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

http://ideone.com/9qp8Hv

【讨论】:

  • 它只适用于一个条目,在同一行添加更多条目并再次测试:) eval.in/767366eval.in/767370
  • 只需要将它应用到每一行;)
  • 我同意,但你需要指定它;)
【解决方案2】:

如果您的模式总是与您在示例中显示的相同,即 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).
) 

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

【讨论】:

    猜你喜欢
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多