我有一个包含集合字符串的文件。所有字符串都以相同的字符集开头,以相同的字符结束。我需要找到与某个模式匹配的所有字符串,然后在保存文件之前从它们中删除特定的字符。每个字符串如下所示:
Data_*: " ... "对于每个字符串,Data_是相同的,星号是一个递增的整数,它要么是2位,要么是3位,而冒号和双引号对于每个字符串是相同的。...在每个字符串中都是完全不同的,它是我需要处理的每个字符串中的一部分。我需要从...中删除所有双引号,同时保留封闭的双引号。我不需要更换它们,只需把它们移除。
例如,我需要这个..。
Data_83: "He said, "Yes!" to the question"变成这样..。
Data_83: "He said, Yes! to the question"我对PHP很熟悉,我想使用这个。我知道怎么做像..。
<?php
$filename = 'path/to/file';
$content = file_get_contents($filename);
$new_content = str_replace('"', '', $content);
file_put_contents($filename, $new_content);我确信正则表达式将是我希望用来查找字符串和删除额外双引号的表达式。但是我对正则表达式非常陌生,这里需要一些帮助。
编辑:
我应该提到,该文件是一个包含对象的PHP文件。看起来有点像这样:
<?php
$thing = {
Data_83: "He said, "Yes!" to the question",
Data_84: "Another string with "unwanted" quotes"
}发布于 2017-12-05 09:20:35
没有那么优雅,但是您可以创建一个UDF:
function RemoveNestedQuotes($string)
{
$firstPart = explode(":", $string)[0];
preg_match('/"(.*)"/', $string, $matches, PREG_OFFSET_CAPTURE);
$tmpString = $matches[1][0];
return $firstPart . ': "' . preg_replace('/"/', '', $tmpString) . '"';
}示例:
$string = 'Data_83: "He said, "Yes!" to the question"';
echo RemoveNestedQuotes($string);
// Data_83: "He said, Yes! to the question" 发布于 2017-12-05 08:53:32
您可以在正则表达式中使用preg_replace_callback,如
'~^(\h*Data_\d{2,}:\h*")(.*)"~m'请注意,如果在行尾指定一个可选的,:'~^(\h*Data_\d{2,}:\h*")(.*)",?\h*$~m',可能会使它更安全,但是您可能需要引入另一个捕获组(围绕,?\h*,然后在preg_replace_callback回调函数中添加$m[3] )。
详细信息
^ -行的开始(m是一个多行修饰符)(\h*Data_\d{2,}:\h*") -第1组($m[1]):\h* - 0+水平白空间Data_ - Data_子字符串\d{2,} -2或更多位数: -一个冒号\h* - 0+水平白空间" -双引号
(.*) -第2组($m[2]):除行中断字符以外的任何0+字符,尽可能多,直到最后一个." -双引号(行)。$m表示整个match对象,您只需要在$m[2]中删除",这是第二个捕获。
preg_replace_callback('~^(\h*Data_\d{2,}:\h*")(.*)"~m', function($m) {
return $m[1] . str_replace('"', '', $m[2]) . '"';
}, $content);发布于 2017-12-05 08:44:26
在str_replace之后,再用implode和explode再走一步。你就这样做吧。
<?php
$string = 'Data_83: "He said, "Yes!" to the question"';
$string = str_replace('"', '', $string);
echo $string =implode(': "',explode(': ',$string)).'"';
?>程序输出
Data_83: "He said, Yes! to the question"只是为了替换"引号
<?php
$string = 'Data_83: "He said, "Yes!" to the question"';
echo preg_replace('/"/', '', $string);
?>https://stackoverflow.com/questions/47649232
复制相似问题