开发者

Replacing variables in text with random values

I have a block of text that contain开发者_开发技巧s a variable:

Hello my name is john #last# 

I have 20 different last names in a array that can be used, how can I replace #last# with a random last name from the array? Meaning how can I read between the #'s and get "last" then use that to determine which array to grab from and input a random value


preg_replace_callback() could be your friend.

Basic example:

$s="Hello my name is John #last#";

function random_name($m) {
    $a=array('Fos', 'Smith', 'Metzdenafbuhrer', 'the Enlightened');
    foreach ($m as $match) {
        return $a[array_rand($a)];
    }
}

$news=preg_replace_callback('/#last#/', 'random_name', $s);

UPDATE: I created another example for you, with more flexibility:

$s="Hello #title#, my name is John #last#";

function random_name($m) {
    $a=array(
        'last' => array('Fos', 'Smith', 'Metzdenafbuhrer', 'the Enlightened'),
        'title' => array('Honey', 'Boss', ', I am your father'),
        );
    foreach ($m as $match) {
        $v=trim($match, '#');
        return $a[$v][array_rand($a[$v])];
    }
}

$news=preg_replace_callback('/(#[a-z]+#)/', 'random_name', $s);


You can user sprintf like

<?php
    $str = 'Hello my name is john %s';
    printf($str, $name);
?>


<?php

$random_last_names = array("Smith", "Jones", "Davis");
$string = "Hello my name is john #last#";

$random_last_name_id = rand(0, count($random_last_names));

$new_string = preg_replace("/#last#/", $random_last_names[$random_last_name_id], $string);
?>

Or better yet, use printf like fabrik said, but you can use this rand() method to select a name.


Or you can use preg_replace with the /e PREG_REPLACE_EVAL modifier:

$str = '...' // your input text
$names = array('smith', 'brown', 'white', 'red');

echo preg_replace('/#last#/e', '$names[rand(0, count($names) - 1)]', $str);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜