如何检查多行字符串并引用它


How can I check for a string over multiple lines and quote it?

我必须修复一个 YAML 文件。我必须检查文件中的文本字段(我可以忽略所有其他字段)。如果内容没有引用,我想设置这些引用。

text: - Any text

应该返回

text: "- Any text"

所以我逐行检查原始文件以创建一个新文件:

while(!feof($file)){
    $line = fgets($file);
    $re = "/text:'s*'K([^'"]+?)$/m";
    $subst = "'"$1'""; 
    $result = preg_replace($re, $subst, $line);
    fwrite($new_file, $result); // Write line to a new file     
}

但是,如果文本包含多行,则不起作用。

这是目前发生的事情:

text: - Any text'n
    which has more
    then one
    line
format: do nothing with that

这应该是:

text: "- Any text'n
    which has more
    then one
    line"
format: do nothing with that

如何检查多行并在缺少引号时添加引号?
如果引号已经设置,则这些行不应发生任何变化。

您可以使用:

$result = preg_replace('/text:'s*'K(.+?)(?='R^'w+: )/ms', "$1", $line);

正则表达式演示

(?='R^'w+: )是一个展望,将确保匹配,直到下一行是一些word:

text:'s*'K(['s'S]+?)(?='n[^'s]+|$)

试试这个。替换为 "$1" 。请参阅演示。

https://regex101.com/r/iS6jF6/14

$re = "/text:''s*''K([''s''S]+?)(?=''n[^''s]+|$)/i";
$str = "text: - Any text'ntext: - Any text'n'n which has more'n then one'n line'nformat: do nothing with that'ntext: - Any text";
$subst = "'"$1'"";
$result = preg_replace($re, $subst, $str);

试试这个

<?php
 $str="Text: -any text";
 $pattren=array();
 $pattern[0]="/'-/";
 $replacement=array();
 $replacement[0]="'"-";
  echo preg_replace($pattern,$replacement,$str);?>

演示 : https://eval.in/299211