0

簡単なテキストがあるとしましょう:

テスト テスト テスト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');

これを達成する方法:

テスト テスト テスト pzfAdmAtYIY Samsung Mobile USA - El Plato Supreme より多くのテストとランダム テキスト UZQ_RDb0lcE SET FIRE | ダブステップ詳細テキストなど

私の試み:

$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 more testing and random text UZQ_RDb0lcE Samsung Mobile USA - El Plato Supreme more text など

どんな助けでも素晴らしいでしょう。

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() : 例は次の規則に従っているため、2 番目のパラメーターは置換配列である必要があります。「このパラメーターが文字列で、パターン パラメーターが配列の場合、すべてのパターンがその文字列に置き換えられます」。

また、正規表現のドットにも注意してください。エスケープする必要があります。

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

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

于 2013-02-02T22:07:02.063 に答える