我有文本塊包含變量:文本與隨機值替換變量
Hello my name is john #last#
我有一個數組中的20個不同姓氏可以使用,我怎麼能代替#最後#與數組中的隨機姓氏?這意味着我怎麼能#的念之間,並得到‘最後’,然後用它來確定從輸入一個隨機值搶哪個數組
我有文本塊包含變量:文本與隨機值替換變量
Hello my name is john #last#
我有一個數組中的20個不同姓氏可以使用,我怎麼能代替#最後#與數組中的隨機姓氏?這意味着我怎麼能#的念之間,並得到‘最後’,然後用它來確定從輸入一個隨機值搶哪個數組
preg_replace_callback()可能是你的朋友。
基本例如:
$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);
更新:我創造了另一個例子對你來說,有更多的靈活性:
$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);
感謝您的回覆!唯一的問題是#之間的單詞可以是大約5個不同的單詞,是否可以在#之間使用通配符並獲取文本以查看要使用哪個數組? – jamal 2011-03-24 07:53:02
您可以通過用戶sprintf像
<?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);
?>
或者更好的是,像fabrik說的那樣使用printf,但是你可以使用這個rand()方法來選擇一個名字。
或者你可以使用preg_replace
與/e
PREG_REPLACE_EVAL
修改:
$str = '...' // your input text
$names = array('smith', 'brown', 'white', 'red');
echo preg_replace('/#last#/e', '$names[rand(0, count($names) - 1)]', $str);
是這個一個家庭作業問題?如果是Jamal,給它一個作業標籤,讓人們給你額外的幫助。 – 2011-03-24 07:41:24