duanlun2827 2011-08-28 03:15
浏览 151
已采纳

正则表达式查找双引号php中的所有子串

I have a big database that has fields of paragraphs that are formatted like this:

["This is the first sentence", "This is the second sentent", "This is the third sentence", "This is the fourth sentence"]

I would like to extract the (using PHP) and put them in an array where each array element is a sentence. Right now, I am using this:

$trim_joined = substr($joined, 2, -2); //gets rid of the first and last bracket and double quote
$sentences = explode('", "', $trim_joined);

It seems a bit fragile because I am not 100% sure that this field follows this exact same format for every row of the database (over 350,000 rows). I was wondering if there is a regular expression that extracts ALL elements of the strings that are inside double quotes and puts them in an array. This way, I don't have to worry if there are entries without the brackets at beginning and end.

Unfortunately, i now little to nothing about regex so asking for help. Thanks in advance

  • 写回答

2条回答 默认 最新

  • douzhong3887 2011-08-28 03:22
    关注

    If the format was consistent you could just use json_decode - as the rows are pretty much lists of strings. I would totally test that first, even if it runs a few minutes.

    Failing that you can use a somewhat more robust CSV parser, after simply triming the square brackets (I would conjecture that's the optimum approach here):

     $strings = str_getcsv(trim(trim($row, "["), "]"));
    

    The simplest regex solution would be:

     preg_match_all('/"([^"]*)"\K/', $row, $strings);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器