0

我需要用逗号替换一个简单的文本来编号。

CSV File: 

Test1
Test1, Test2
Test1, Test2, Test3

php代码

$text = "Test1";
$text1 = "Test1, Test2";
$text1 = "Test1, Test2, Test3";

$search = array('$text','$text1','$text2');
$replace = array('10','11','12');
$result = str_replace($search, $replace, $file);
echo "$result";

结果是: "10","10, 11","10, 11, 12"

但我想得到“10”、“11”、“12”。

这是最终脚本,但其中一个我得到“10、12”

$text1 = "Test1";
$text2 = "Test2";
$text3 = "Test3";
$text4 = "Test1, Test2, Test3";
$text5 = "Test1, Test2";
$text6 = "Test1, Test3";
$text7 = "Test2, Test3";
$text8 = "Blank";
array($text8,$text7,$text6,$text5,$text4,$text3,$text2,$text1);
array('10','11','12','13','14','15','16','17');
4

1 回答 1

1

您可能不想拥有这些字符串文字:

$search = array('$text','$text1','$text2');

尝试

$search = array($text,$text1,$text2);

当你使用单引号时,变量不会被解析,所以

$text1 = 'Hello';
$text2 = '$text1';
echo $text2; // $text1

VS

$text1 = 'Hello';
$text2 = $text1;
echo $text2; // Hello

结果来自:

Test1
Test1, Test2
Test1, Test2, Test3

将是 Test1 的每个实例都替换为 10,依此类推 - 所以:

10
10, 11
10, 11, 12

更新

我明白你在做什么。当你将数组传递给str_replace它时,它会按顺序处理它们——所以当它寻找Test1, Test2你的时候,你已经Test1用 10 个替换了。颠倒顺序做你想做的事......

$text = "Test1";
$text1 = "Test1, Test2";
$text2 = "Test1, Test2, Test3";

$search = array($text2,$text1,$text); // reversed
$replace = array('12', '11', '10');// reversed
$result = str_replace($search, $replace, $file);
echo $result;
于 2012-11-16T16:37:15.083 回答