PHP-替换文本而不覆盖已替换的文本

时间:2018-08-19 13:25:26

标签: php replace

我想替换字符串中的特定字符,而无需再次替换它们。这是我在说的:

// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);

// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a', 'p');
$fruit   = array('apple', 'pear');
$text    = 'a p';
$output  = str_replace($letters, $fruit, $text);
echo $output;

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

@NiettheDarkAbsol建议使用strtr函数替换文本的示例代码

<?php 

$replacepair  = array('A' => 'B', 'B' =>'C', 'C'=>'D', 'D'=>'E', 'E'=> 'F');
$subject = 'A';

echo strtr($subject, $replacepair); // outputs B

答案 1 :(得分:0)

首先将其替换为文本中未包含的某些字符。以后将它们替换为您想要的。

$letters = array('a', 'p');
$fruit   = array('*', '#');
$text    = 'a p';
$output  = str_replace($letters, $fruit, $text);

$letters = array('*', '#');
$fruit   = array('apple', 'pear');
$output  = str_replace($letters, $fruit, $output);
echo $output;