0

假设我有一个简单的文本:

testing testing testing http://www.youtube.com/watch?v=pzfAdmAtYIY 更多测试和随机文本 http://www.youtube.com/watch?v=UZQ_RDb0lcE更多文本等

我也有简单的数组:

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

如何实现这一点:

testing testing testing pzfAdmAtYIY Samsung Mobile USA - El Plato Supreme 更多测试和随机文本 UZQ_RDb0lcE SET FIRE | DUBSTEP 更多文字等

我的尝试:

$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;

结果很不幸:

testing testing testing pzfAdmAtYIY Samsung Mobile USA - El Plato Supreme 更多测试和随机文本 UZQ_RDb0lcE Samsung Mobile USA - El Plato Supreme 更多文本等

任何帮助都会很棒。

4

2 回答 2

2

你可以用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;
于 2013-02-02T22:17:56.573 回答
0

preg_replace() :第二个参数必须是替换数组,因为您的示例遵循以下规则:“如果此参数是字符串且模式参数是数组,则所有模式都将被该字符串替换”。

还要注意正则表达式中的点:它们必须被转义。

结果: $string = preg_replace('regex', $arr, $text);

http://php.net/manual/en/function.preg-replace.php

于 2013-02-02T22:07:02.063 回答