字符串替换为变量数组

时间:2015-07-21 22:16:06

标签: php arrays str-replace

好的,如果我使用代码:

$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");
$newphrase = str_replace($healthy, $yummy, $phrase);

// Provides: You should eat pizza, beer, and ice cream every day

但是如果我要替换的单词列表是变量怎么办。

$sample1 = "fruits, vegetables, fiber";
$sample2 = "pizza, beer, ice cream";
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array($sample1);
$yummy   = array($sample2);
$newphrase = str_replace($healthy, $yummy, $phrase);

// Provides: You should eat fruits, vegetables, and fiber every day.

如果我使用相同:

$sample1 = '"fruits", "vegetables", "fiber"';
$sample1 = '"pizza", "beer", "ice cream"';
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array($sample1);
$yummy   = array($sample2);
$newphrase = str_replace($healthy, $yummy, $phrase);

我错过了什么吗?

有没有办法轻松做到这一点?

2 个答案:

答案 0 :(得分:0)

你需要将字符串转换为数组,在这种情况下使用explode:

$sample1 = "fruits, vegetables, fiber";
$sample2 = "pizza, beer, ice cream";
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
    $healthy = explode(',',$sample1);
    $yummy   = explode(',',$sample2);
$newphrase = str_replace($healthy, $yummy, $phrase);

答案 1 :(得分:0)

您可以使用分隔符string array分解为$sample1 = "fruits, vegetables, fiber"; $sample2 = "pizza, beer, ice cream"; $phrase = "You should eat fruits, vegetables, and fiber every day."; $healthy = explode(",", $sample1); $yummy = explode(",", $sample2); $newphrase = str_replace($healthy, $yummy, $phrase);

trim()

我建议您在每个字符串之间没有空格。如果您要这样做,那么您可能希望array_map()每个值。 $healthy = array_map('trim', explode(",", $sample1)); 在这里很有用,因为您可以将函数映射到每个值,如下所示:

$sample1 = "fruits    ,    vegetables,fiber";
$sample2 = "pizza,      beer,ice cream";
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array_map('trim', explode(",", $sample1));
$yummy   = array_map('trim', explode(",", $sample2));
$newphrase = str_replace($healthy, $yummy, $phrase);

所以整件事情更像是:

np.atleast_2d