1

I have a block of text that contains 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

1
  • is this a homework question? If it is Jamal, give it a homework tag for people to give you extra help. Commented Mar 24, 2011 at 7:41

4 Answers 4

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for replying! The only thing is the words between the #'s can be about 5 different ones, is it possible to use wildcard between #'s and grab the text to see which array to use?
0

You can user sprintf like

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

Comments

0
<?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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.