douzhuanfen5923 2015-10-26 17:42
浏览 49
已采纳

RegEx和str_replace,用文本中的PHP中的其他字符串修改字符串

I want to transform a certain number of characters by a string in PHP from a text :

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed fringilla tincidunt justo sed hendrerit. Vivamus [im::17,I] elit id accumsan pulvinar. Fusce ac lacus arcu. Nullam imperdiet imperdiet eros, [im::31,R] congue libero. Aliquam non bibendum nisi. Nunc pretium feugiat nunc ut volutpat. Maecenas finibus viverra justo, quis luctus [im::11,L] facilisis vel.

So what I try to do is to replace this :

[im::31,R]

By this:

<img src='img_31_0px.jpg' style='text-align:right;'/>

I got an array for the style inherit, left, right, center, this is not my difficulty.

This is my actual function:

function showimg($txtimg) {
        $fullstr = str_replace("[im::17,I]", "<img src='img_17_0px.jpg' style='text-align:inherit;'/>", $txtimg);
        return ($fullstr);
    }

As you can see, it's static for the moment, and not dynamic. I am looking on http://www.regexr.com/ to try something but it doesn't leed me anywhere.

Can you guys help me with my case, or leed me in the good direction at least? Thanks.

  • 写回答

3条回答 默认 最新

  • duankanyi6539 2015-10-26 18:02
    关注

    Well, to keep the alignment you'll need a callback:

    function showimg($m) {
        $dir = array('I'=>'inherit','R'=>'right','L'=>'left');
        return '<img src="img_'.$m[1].'_0px.jpg" style="text-align:'.$dir[$m[2]].';"/>';
    }
    
    $result = preg_replace_callback('/\[im::([0-9]+),(I|R|L)\]/', 'showimg', $txtimg);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题