【问题标题】:Replace numbers with an identifier用标识符替换数字
【发布时间】:2022-07-07 19:29:32
【问题描述】:

我在存储一些避免重复数据的数据时遇到问题。

我有这些(示例但不工作)两个字符串:

    $text1 = "S0 64000";
    $text2 = "C0 64000";

我的目标是获得类似的东西:

    $newtext1 = "S%d0% %d1%";
    $newtext2 = "C%d0% %d1%";

所以将来我知道在 %d0% 中我会得到第一个数字,在 %d1% 中我会得到第二个(不同的)数字 如果是$text1="S0 0" 可以有$newtext1 = "S%d0% %d0%"

例如,如果给$text1 = S10 455,我将在自动返回C10 455 中计算text2 我再说一遍,这是我发现此问题的示例字符串,该字符串也可以是没有数字的长文本,因此该字符串并不总是具有相同的语法。

目前我的流程是这样的:

    $text1 = "S0 64000";
    $text2 = "C0 64000";

    $pattern = '/\d+/';

    /* get the count and the number founded storing in $matchOriginal */
    $cnt = preg_match_all($pattern,$text1,$matchOriginal);

    if($cnt == 0){
        dd("no numbers"); //just for test
    }
    /* i get the numbers founded in $text2
    preg_match_all($pattern,$text2,$matchTransl);

    /* I check that each two arrays of numbers are equal, maybe can be done in a better way */
    $original = array_diff($matchOriginal[0],$matchTransl[0]);
    $transl = array_diff($matchTransl[0],$matchOriginal[0]);

    if(empty($original) && empty($transl)){
    } else {
        dd("different arrays");
    }


    /* I prepare two arrays
    $replacement will be %d0%, %d1% the number will depends by the number presence on 
    the string
    $values will be the array with the numbers i will replace with $replacement*/

    foreach($matchOriginal[0] as $key => $value){
        $replacement[] = "%d".$key."%";
        $values[] = $value;
        
    }

    /* here the magic */
    $newText1 = str_replace($values, $replacement, $text1);
    $newText2 = str_replace($values, $replacement, $text2);

但我有一个问题,因为目前流程正在运行,$values$replacement 数组是这样的:

^ array:2 [▼
  0 => "0"
  1 => "64000"
]
^ array:2 [▼
  0 => "%d0%"
  1 => "%d1%"
]

函数str_replace 将开始用%d0% 替换所有"0",结果字符串将是:

$text1 ="S%d0% 64%d0%%d0%%d0%"

有没有更好的解决方案来将数组从大到小排序?

也许我可以使用 preg_replace,但如何构建正则表达式?

【问题讨论】:

    标签: php


    【解决方案1】:

    我会使用preg_replace_callback,如果你将它与计数器变量结合使用,那么你就不必预先提供编号的替换文本。

    $text1 = "S0 64000";
    $c = 0;
    $newtext1 = preg_replace_callback('/\d+/', function($matches) use (&$c) {
      return '%d'.($c++).'%';
    }, $text1);
    unset($c);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      相关资源
      最近更新 更多