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

Prge\u replace在php中工作不正常

  •  0
  • suresh  · 技术社区  · 6 年前

    `$test_numbers_4 = '\\;\\3;4;5'; 
    

    3,4,5

    这是我的密码

    $test_numbers_4 = '\\;\\3;4;5';
    printf( "<h4>Task 4:</h4>\n" ); 
    $str = preg_replace('/\s{0,}/', '', $test_numbers_4); 
    $str1 = preg_replace('/\\\\\\|;\\\\/', ',', $str); 
    $array = explode(',', $str1);
    $res=implode( ',', $array) ;
    echo $res;
    

    输出 : 3,4,5

    Edit:
    

    $string =\\,\\2,7,-3,5,-2 如果字符串是这样的,当我运行文件,我想显示错误消息说 negative numbers -3,-2 not allowed.

    但这并没有给我预期的结果

    有人能帮我解决问题吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Nick SamSmith1986    6 年前

    看起来你在试图扔掉那些不是数字或数字的东西 ; preg_replace 删除不需要的字符 preg_split ; ,与 PREG_SPLIT_NO_EMPTY

    $test_numbers_4 = '\\;\\3;4;5';
    $str = preg_replace('/[^\d;]/', '', $test_numbers_4); 
    $array = preg_split('/;/', $str, -1, PREG_SPLIT_NO_EMPTY);
    $res=implode(',', $array) ;
    echo $res;
    

    3,4,5
    

    如果您特别想删除空格和双反斜杠,请使用以下preg\u替换:

    $str = preg_replace('/\\\\|\s+/', '', $test_numbers_4); 
    
        2
  •  1
  •   A l w a y s S u n n y    6 年前

    你可以尝试以下步骤来获得你需要的-

    1. 使用删除所有非数字字符 preg_replace()
    2. str_split()
    3. 使用逗号将其内爆 implode()

    演示: https://3v4l.org/IKoYt