doushan5222 2013-11-05 16:16
浏览 212
已采纳

替换正则表达式的所有匹配项,第一个匹配项除外

I'm not sure if this is possible only with preg_replace function but I would like to get only the first image and ignore all the other.

This code excludes all images in the text I want to display, but I need to get only the first image.

if (!$params->get('image')) {
    $item->introtext = preg_replace('/<img[^>]*>/', '', $item->introtext);
}

Can you please point me to the right direction to achieve this?


EDIT :

It seems that using the limit property is not enough since I don't want to skip the 1st image and keep the remaining. I need the opposite: Keep the 1st image and replace all the others.

  • 写回答

1条回答 默认 最新

  • dpn68721 2013-11-05 16:18
    关注

    You can use preg_replace_callback to accomplish that. This function will execute a callback function you pass as parameter that will return a replacement string for every match it founds in your original string.

    In this case, we will return the own match in the first occurrence so it will not be replaced.

    $i = 0;
    $item->introtext = preg_replace_callback('/<img[^>]*>/', function($match) use (&$i) {
        if ($i++ == 0) // compares $i to 0 and then increment it
            return $match[0]; // if $i is equal to 0, return the own match
    
        return ''; // otherwise, return an empty string to replace your match
    }, $item->introtext);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题