如何将定义的字符串(即cite:
)后面的文本放入引号(如果它尚未引用)?可选的,行的开头可以有多个空格。
cite: Lorem ipsum
cite: Lorem ipsum
cite: "Already quoted"
应该成为
cite: "Lorem ipsum"
cite: "Lorem ipsum"
cite: "Already quoted"
我的尝试:
preg_replace("/[\s\t]cite:[\s\t]/","",$line);
但我没有正确理解。这些是我的问题:
cite:
(有空格),我希望得到余下的内容答案 0 :(得分:1)
你可以使用这样的正则表达式:
^(\s*cite: )([\w\s]+)$
<强> Working demo 强>
并使用替换字符串:
$1"$2"
请查看以下Substitution
部分:
php代码将是:
$re = "/^(\\s*cite: )([\\w\\s]+)$/m";
$str = "cite: Lorem ipsum\n cite: Lorem ipsum\ncite: \"Already quoted\"";
$subst = "$1\"$2\"";
$result = preg_replace($re, $subst, $str);
答案 1 :(得分:1)
或使用此模式
cite:\s*\K([^"]+?)$
并替换为"$1"
Demo
cite: # "cite:"
\s # <whitespace character>
* # (zero or more)(greedy)
\K # <Reset start of match>
( # Capturing Group (1)
[^"] # Character not in [^"]
+? # (one or more)(lazy)
) # End of Capturing Group (1)
$ # End of string/line