Php 用preg_replace删除外部引号
我的文件中有以下行:Php 用preg_replace删除外部引号,php,preg-replace,Php,Preg Replace,我的文件中有以下行: normal line "line in quotes" line with "quoted" word line with quotes word at "end" "quoted line with quoted word at "end"" 我只需要删除外部引号 结果: normal line line in quotes line with "quoted" word line with quotes word at "end" quoted li
normal line
"line in quotes"
line with "quoted" word
line with quotes word at "end"
"quoted line with quoted word at "end""
我只需要删除外部引号
结果:
normal line
line in quotes
line with "quoted" word
line with quotes word at "end"
quoted line with quoted word at "end"
这可以用一个preg\u replace()
来完成吗?类似这样的东西:
$result = preg_replace('~^"((?:[^"\r\n]+|"[^\r\n"]*")*+)"$~m', '$1', $text);
图案详情:
~ # pattern delimiter
^ # anchor for the begining of the line
" #
( # open the capture group 1
(?: # non-capturing group, content of a line between quotes:
[^"\r\n]+ # - all that is not a quote or a newline
| # OR
"[^\r\n"]*" # - a substring between quotes
)*+ # repeat the group zero or more times
) # close the capture group
" #
$ # anchor for the end of the line
~m # multiline modifier to change ^ and $
Preg_replace没有“如果”之类的词来表示“如果开头和结尾都有引用”。因此,您必须表达两种可能性:
$r = preg_replace('/^"(.*)"$|^(.*)$/', '$1$2', $b);
|的左边匹配一行,开头和结尾都是“1”。如果不匹配,$1为空。|的右边匹配任何其他内容,其中$2为内容。如果左边匹配,则不会转到右边