[英]Replace phrase in a string
我要替换给定格式的特定字符串。 请查看突出显示的短语以获取区别。
'67,Yoga Pura, “ N。7th Street 15440,Suite 1” ,凤凰城,亚利桑那州,85022,-112.066286,33.627028,26'
进入
'67,Yoga Pura, 15440 N.7th Street Suite 1 ,Phoenix,AZ,85022,-112.066286,33.627028,26'
我正在尝试删除用双qoutes括起来的短语中的逗号。 我知道如何替换它,但我不知道如何在变量中设置此短语“ 15440 N. 7th Street,Suite 1” 。
$lines = preg_replace('/"[^"]+"/', 'new formatted text', $lines);
请帮忙
使用正则表达式的另一种方法:
$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
您可以匹配双引号之间的所有句段,然后使用回调函数从中去除双引号/逗号:
$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);
尝试这个:
$text = preg_replace('/^(.*)"([^"]*),([^"]*)"(.*)$/', '${2}${3}', $text);
以便隔离"
和"
之间的部分,
或这个 :
$text = preg_replace('/"([^"]*),([^"]*)"/', '${1}${2}', $text);
只是删除,
之间"
。
似乎运作良好
您可以提前使用
/,(?=(([^"]*"[^"]*"[^"]*[^"]*"[^"]*)+|[^"]*"[^"]*)$)/
---------------------------- _ ----------
| | |->matches a single odd " till end
| |->OR
|-> matches 1 to many occurrences of 3 " till end
因此,这将匹配,
只有当它有奇数个 "
其次是它
显然,这不适用于嵌套的"
可能有一些速记回调切片'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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.