dozrhldy285751 2018-01-15 10:33
浏览 30
已采纳

preg_replace子串在特定位置

I have values, which look like so:

Point_10_5_80_...
Point_22_21_77_...

Dots mean that pattern continues. Such values serve as templates in my code. And I want to be able to replace only second number in each template:

Point_10_5_80_... -> Point_10_777_80_...
Point_22_21_77_... -> Point_22_888_77_...

So, in first template 5 was replaced with 777 and in second template 21 was replaced with 888. I'm not sure how to implement this with preg_replace. I tried

$values = preg_replace('(Point_\d+_)(\d+)([_0-9]+)','$1' . $replacement . '$3', $template);

but in this case I just get empty values

  • 写回答

1条回答 默认 最新

  • dphe5602 2018-01-15 10:50
    关注

    Your code has two errors: First of all you did not escape your pattern. To do so you can use slashes: $pattern = '/(Point_\d+_)\d+((?:_\d+)*)/' (The pattern is equivalent to your pattern, i just reformed it)

    The other problem is, that your $replacement variable will contain a number itself. So by concatenating it with $1 and $2 you will get something like $1777$2. This is red as: Take group 17, add the number 77, then add group 2, which is not what you want. This is because there are a maximum of 100 groups (0 ~ 99) and it will always take two digits for the group identifier, if provided. To solve this prefix your groups with a 0: ' $01' . $replacement . '$02' to provide both digits. (It is not really necessary for group 2, because you do not add any number behind it.)

    Your code then may look like this:

    $array = ['Point_10_5_80_111','Point_22_21_77_222','Point_21_55_77_222'];
    $replacements = [777, 888, 999];
    $pattern = '/(Point_\d+_)\d+((?:_\d+)*)/';
    
    $values = array_map(function($string, $replacement) use ($pattern) {
        return preg_replace($pattern, '$01' . $replacement . '$02', $string);
    }, $array, $replacements);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP