English 中文(简体)
Regex和用preg_replace替换双撇号
原标题:Regex and replacing double apostrophes with preg_replace

我有几行需要更新,其中双撇号在某些位置被替换,并被删除,但在其他位置没有。

因此:

(2,  Name 2 ,   , 8, 0, 0, 1,  Info blah blah , 0, 4), 
(3,  Name 3 ,  A normal bit of information , 8, 1, 0, 1,  Info more blah , 0, 4),
(45,  Name 45 ,  Info with    in it like it  s stuff , 356, 10, 1, 1,   , 0, 9)

需要成为:

(2,  Name 2 ,   , 8, 0, 0, 1,  Info blah blah , 0, 4), 
(3,  Name 3 ,  A normal bit of information , 8, 1, 0, 1,  Info more blah , 0, 4),
(45,  Name 45 ,  Info with    in it like it  s stuff , 356, 10, 1, 1,   , 0, 9)

当尝试各种方法时,我设法更新了所有这些方法,然后中断了以后使用的函数。

最佳回答

嗯,这确实需要一些解析。如果您使用正则表达式,那么它实际上只能在最佳匹配的基础上工作。

如果您可以假设始终是CSV列表中的空字符串,那么查找逗号是一个选项。但是,如果其中一个字符串在双引号后包含逗号,则此操作将失败:

preg_replace("/  (?![,)])/", "\ \ ", $text);

为了增加一些安全性,您可以添加前缀检查,如(?<;=[(s]),但这几乎没有帮助。

问题回答
 (([^ ]*?)( {2})([^ ]*?))+ ([,|)])

这应该能够被<code>$1$4$5</code>所取代,并且将只匹配单引号中的两个单引号,尽管后面在文字中出现逗号。

s/(?<;=)([^,]*)(?=[^,]]*)/$1\\/g

记住,以后不能更改游戏并允许在delimeters()之间使用一个撇号,因为这与()不兼容。好啊

use strict;
use warnings;

my @data = (
"(2,  Name 2 ,   , 8, 0, 0, 1,  Info blah blah , 0, 4), ",
"(3,  Name 3 ,  A normal bit of information , 8, 1, 0, 1,  Info more blah , 0, 4),",
"(45,  Name 45 ,  Info with    in it like it  s stuff , 356, 10, 1, 1,   , 0, 9)",
"       ,    ,    ",
);

for (@data) {
    print "
$_
";
    if (
          s/ (?<= )([^ ,]*)    (?= [^ ,]* )/$1\ \ /xg
       )
    {
       print "==>	$_
";
    }
}

Output:
(2, Name 2 , , 8, 0, 0, 1, Info blah blah , 0, 4),
(3, Name 3 , A normal bit of information , 8, 1, 0, 1, Info more blah , 0, 4),
(45, Name 45 , Info with in it like it s stuff , 356, 10, 1, 1, , 0, 9)
==> (45, Name 45 , Info with in it like it s stuff , 356, 10, 1, 1, , 0, 9)
, ,
==> , ,





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签