替换字符串中的短语

时间:2013-03-20 07:24:05

标签: php regex preg-replace preg-match

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

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

进入

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

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

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

请帮忙

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);

答案 2 :(得分:1)

试试这个:

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

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

或者这个:

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

仅删除,之间的"

似乎运作良好

working example here

答案 3 :(得分:0)

您可以使用前瞻

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

因此,只有,奇数后跟{/ 1>}才会匹配"


显然这不适用于嵌套"

答案 4 :(得分:0)

可能有一些速记回调切片'n合并一线奇迹,但让我们直接做:

$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