-1

我想替换给定格式的特定字符串。请参阅突出显示的短语以获得差异。

'67,Yoga Pura, "15440 N. 7th Street, Suite 1" ,凤凰城,AZ,85022,-112.066286,33.627028,26'

进入

'67,Yoga Pura, 15440 N. 7th Street Suite 1 ,Phoenix,AZ,85022,-112.066286,33.627028,26'

我正在尝试删除由双引号括起来的短语中的逗号。我知道如何替换它,但我不知道如何在变量中设置这个短语“15440 N. 7th Street, Suite 1” 。

$lines = preg_replace('/"[^"]+"/', 'new formatted text', $lines);

请帮忙

4

5 回答 5

2

使用正则表达式的另一种方法:

$str = '67,Yoga Pura,"15440 N. 7th Street, Suite ",Phoenix,AZ,85022,-112.066286,33.627028,26';
echo preg_replace ( '#"(.*?),(.*?)"#', '$1$2', $str );

输出:

67,Yoga Pura,15440 N. 7th Street Suite 1,Phoenix,AZ,85022,-112.066286,33.627028,26
于 2013-03-20T07:36:49.077 回答
1

您可以匹配双引号之间的所有段,然后使用回调函数从它们中去除双引号/逗号:

$string = '67,Yoga Pura,"15440 N. 7th Street, Suite 1",Phoenix,AZ,85022,-112.066286,33.627028,26';

function strip_commas($str) {
  return str_replace(array(',', '"'), '', $str[0]);
}

$string = preg_replace_callback('/".*?"/', "strip_commas", $string);
于 2013-03-20T07:32:02.210 回答
1

尝试这个:

$text = preg_replace('/^(.*)"([^"]*),([^"]*)"(.*)$/', '${2}${3}', $text);

隔离之间的部分"并删除您的,

或这个 :

$text = preg_replace('/"([^"]*),([^"]*)"/', '${1}${2}', $text);

只是为了删除,中间"

它似乎运作良好

这里的工作示例

于 2013-03-20T07:33:41.303 回答
0

您可以使用前瞻

/,(?=(([^"]*"[^"]*"[^"]*[^"]*"[^"]*)+|[^"]*"[^"]*)$)/
       ----------------------------  _ ----------
                   |                 |       |->matches a single odd " till end
                   |                 |->OR
                   |-> matches 1 to many occurrences of 3 " till end

所以,只有当它后面有奇数个时才会匹配"


显然这不适用于嵌套"

于 2013-03-20T07:31:42.070 回答
0

可能有一些速记回调 slice 'n merge one-line-wonder 为此,但让我们直接做:

$row = '67,Yoga Pura,"15440 N. 7th Street, Suite 1",Phoenix,AZ,85022,-112.066286,33.627028,26';
$parsed = str_getcsv($row);
$parsed2 = array();
$i = 0;

while ($col = array_shift($parsed)) {
    array_push($parsed2, str_replace(',', '', $col));
}

https://ignite.io/code/51496970ec221ee821000003

当然,这是str_getcsv()从字符串解析 CSV 行的最简单方法(如果您的 PHP >= 5.3.0)。

略短:

$row = '67,Yoga Pura,"15440 N. 7th Street, Suite 1",Phoenix,AZ,85022,-112.066286,33.627028,26';
$parsed = str_replace(',', '', str_getcsv($row));

print_r($parsed);

echo implode(',', $parsed);

https://ignite.io/code/51496b2bec221ee821000004

于 2013-03-20T07:47:47.657 回答