Prge_replace 在 php 中无法正常工作

Prge_replace is not working properly in php

我正在尝试替换下面的字符串

`$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.

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

任何人都可以帮我解决问题吗?

您似乎在尝试丢弃非数字或 ; 的内容,在这种情况下,您可以使用此代码来完成。它使用 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_replace:

$str = preg_replace('/\\|\s+/', '', $test_numbers_4); 

您可以尝试这个步骤来获得您需要的-

  1. 使用 preg_replace()
  2. 删除所有非数字字符
  3. 使用str_split()
  4. 分隔每个字符
  5. 使用 implode()

    用逗号将其分解

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