douyou7102 2013-02-02 22:02
浏览 30
已采纳

使用数组数据时preg_replace简单文本

Let's just say I have a simple text:

testing testing testing http://www.youtube.com/watch?v=pzfAdmAtYIY more testing and random text http://www.youtube.com/watch?v=UZQ_RDb0lcE more text etc

And I also have simple array:

$arr = array('Samsung Mobile USA - El Plato Supreme', 'SET FIRE | DUBSTEP');

How to achieve this:

testing testing testing pzfAdmAtYIY Samsung Mobile USA - El Plato Supreme more testing and random text UZQ_RDb0lcE SET FIRE | DUBSTEP more text etc

My attempt:

$count = 0;
$text = 'testing testing testing http://www.youtube.com/watch?v=pzfAdmAtYIY more testing and random text http://www.youtube.com/watch?v=UZQ_RDb0lcE more text etc';
$arr = array('Samsung Mobile USA - El Plato Supreme', 'SET FIRE | DUBSTEP');
$string = preg_replace('/http:\/\/www.youtube.com\/watch\?v=([a-zA-Z0-9_-]*)/ms', ' \\1 '. $arr[$count++].'', $text);
print $string;

Unforunately the result:

testing testing testing pzfAdmAtYIY Samsung Mobile USA - El Plato Supreme more testing and random text UZQ_RDb0lcE Samsung Mobile USA - El Plato Supreme more text etc

Any help would be great.

  • 写回答

2条回答 默认 最新

  • duanhuang3074 2013-02-02 22:17
    关注

    You could do something like this with preg_replace_callback:

    $str = 'testing testing testing http://www.youtube.com/watch?v=pzfAdmAtYIY more testing and random text http://www.youtube.com/watch?v=UZQ_RDb0lcE more text etc';
    
    // either like this:
    // $arr = array('Samsung Mobile USA - El Plato Supreme', 'SET FIRE | DUBSTEP');
    // or via $GLOBALS array
    $GLOBALS['arr'] = array('Samsung Mobile USA - El Plato Supreme', 'SET FIRE | DUBSTEP');
    
    
    $str = preg_replace_callback('/http:\/\/www.youtube.com\/watch\?v=([a-zA-Z0-9_-]*)/ms', function($match) {
        // this is called for each match of the expression
    
        // sets a counter
        static $count = 0;        
    
        // making $arr a global variable
        // global $arr;
    
        // the return value
        // $r = $arr[$count];
        // or in case it is in the $GLOBALS
        $r = $GLOBALS['arr'][$count];
        // increase the counter
        $count++;
        // and return
        return $r;
    }, $str);
    
    echo $str;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图