Dar
Dar

Reputation: 169

Replace text to number php

I need to replace a simple text with comma inside to number.

CSV File: 

Test1
Test1, Test2
Test1, Test2, Test3

php code

$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";

the result is: "10","10, 11","10, 11, 12"

but I want to get "10","11","12".

This is the final script but on one of this im getting "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');

Upvotes: 0

Views: 164

Answers (1)

Fenton
Fenton

Reputation: 250932

You probably don't want to have these string literals:

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

Try

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

When you use single-quotes, variables are not parsed, so

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

Vs

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

The result from:

Test1
Test1, Test2
Test1, Test2, Test3

Would be that each instance of Test1 is replaced with 10, and so on - so:

10
10, 11
10, 11, 12

Update

I see what you are trying to do. When you pass arrays into str_replace it processes them in order - so by the time it looks for Test1, Test2 you have already replaced Test1 with 10. Reverse the order to do what you want...

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

Upvotes: 1

Related Questions