如何在字符串的每行的开头和结尾添加引号


How to add a quotation mark to the beginning and end of each line in a string in php

我试图取一个部分逗号分隔设置中的字符串。我需要在字符串中每行的开始和结束处添加引号或其他标记。所讨论的字符串有许多行,如下所示。

IE

2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres

将变成

"2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres"

我尝试过很多次正则表达式,但是我不得不承认我对正则表达式的理解很差。

您可以滥用.不匹配换行符的事实。

$result = preg_replace('/(.+)/', '"$1"', $subject);

我假设字符串是多行长?

我很想创建一个包含每一行的新数组,像这样:

<?php 
$string = '2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres'; // obviously use a string with multiple lines, but i'm just taking your example
$array = preg_split('/'n+/', $string, -1, PREG_SPLIT_NO_EMPTY);
foreach($array as $k=>$v){
  $array[$k]='"'.$v.'"';
}
print_r($array);

或者你也可以直接用

<?php
$newstring = '"'.str_replace("'n", "'"'n'"",$string).'"';

虽然,第二个方法可能需要一点改进,以考虑"'r"或"'r'n"。

如果你的字符串是:

2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres
2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres
2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres
2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres
2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres
2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres

你只需要在每行的开头和结尾加上双引号,你可以使用strtr:

$sLines = "2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres
2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres
2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres
2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres
2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres
2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres";
$arrTr = array();
$arrTr1 = array();
$arrTr[chr(13)] = '"'.chr(13).'"';
$arrTr1["'"'n"] = '"';
$sLines = strtr(strtr($sLines,$arrTr),$arrTr1);
$sLines = '"'.$sLines.'"';
echo '<pre>';
print_r($sLines);
echo '</pre>';

但是,如果你有用"'n"字符粘合的行,你可以这样做:

$sLines = "2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres'n2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres'n2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres'n2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres'n2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres'n2011.11.12 20:06,Teac Ous,Solid Pyroxeres,46521,Pyroxeres";
$arrTr = array();
$arrTr1 = array();
$arrTr["'n"] = '"'."'n".'"';
$sLines = strtr($sLines,$arrTr);
$sLines = '"'.$sLines.'"';
echo '<pre>';
print_r($sLines);
echo '</pre>';