代码之家  ›  专栏  ›  技术社区  ›  Sam

删除逗号后的空格和“或此符号前后的空格”

  •  0
  • Sam  · 技术社区  · 8 年前

    我有像下面这样的文本,我需要删除逗号后的空格和'(单引号)或这个符号前后的空格'(单引号)

    $text = "'game', ' open world', ' test rpg'"
    

    预期结果

    $text = "'game','open world','test rpg'"
    

    我试过下面这一个,但是把每个地方都拆了

    $tested = preg_replace('/\s+/', '', $text);
    
    6 回复  |  直到 8 年前
        1
  •  1
  •   Mihai Matei    8 年前
    echo preg_replace('/\s+?\'\s+?/', '\'', $text);
    
        2
  •  0
  •   Nageen    8 年前

    简单快速的解决方案只需使用PHP explode implode 功能

    echo $text = "'game', ' open world', ' test rpg'";
    print_r(implode(',',explode(',', $text)));
    
        3
  •  0
  •   abhijeet.supekar    8 年前

    试试这个:

    <?php
    $text = "'game', ' open world', ' test rpg'";
    $str = explode(",",$text);
    $arr = array();
    foreach ($str as $key) {
        array_push($arr, trim($key));
    }
    
    print_r(implode(',',$arr));
    ?>
    

    查看这些PHP函数 implode explode

        4
  •  0
  •   Lovepreet Singh    8 年前

    以下模式应该有效。

    Regexr

    代码:

    $text = "'game', ' open world', ' test rpg'";
    
    echo preg_replace('/(\s?\'\s?)/', "'", $text);
    
        5
  •  0
  •   CertainPerformance    8 年前

    前面的regex答案不解释逗号后的空格(而不是逗号前的空格) ' )例如 open, world . 下面是一个适用于逗号和空格的解决方案:

    $text = "'game', ' open, world', ' test ' rpg'";
    echo preg_replace("/(?: *(?='))([',]) */", '$1', $text);
    
        6
  •  0
  •   Tom    8 年前

    选项1:

    $text  = explode("', ' ",$text);
    $text = implode("','",$text);
    

    选项2:

    $text = str_replace("', ' ","','",$text)