使用带有PHP的str_replace()函数更改字符串

时间:2015-08-31 19:36:24

标签: php string str-replace

我该如何改变:

public class MyService extends Service {
    private Handler mainHandler;
    private Timer timer;

    public void onStartCommand(final Intent intent, final int flags, final int startId) {
        mainHandler = new Handler(getApplicationContext().getMainLooper());
        timer = new Timer();
        timer.schedule(new MyTimerTask(), 10000, 10000);
    }

    public void onDestroy() {
        timer.cancel();
    }

    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            mainHandler.post(new Runnable() {
                @Override
                public void run()  {
                    Toast.makeText(getApplicationContext(), "Text to display", Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}

有这个:

[ "Aluno1": 65.8, "Aluno2": 0.3, "Aluno3": 34.9 ]

可能会将['dafa', 43.00],['adfasdf', 13.00],['cu', 0.00] 更改为:,更改为,,但如何使用][进行更改?

4 个答案:

答案 0 :(得分:0)

要使用str_replace(),您可以用%包装想要更改的内容,然后应用。以下示例;

$old_sentence = "My name is %name%";
$new_sentence = str_replace('%name%', 'ADAM', $old_sentence);
echo $new_sentence;

"我的名字是ADAM"

希望这可以让您了解如何使用它。

答案 1 :(得分:0)

看起来你需要json_decode($ array);

所以喜欢:

$your_array=[ "Aluno1": 65.8, "Aluno2": 0.3, "Aluno3": 34.9 ];
json_decode($your_array);

但是json很高兴有数组为什么要将它转换回来?

答案 2 :(得分:0)

这是答案。事实上,简单地将“:”替换为“,”就更复杂了。试试这个:

$Stringtoreplace = '[ "Aluno1": 65.8, "Aluno2": 0.3, "Aluno3": 34.9 ]';


$NewStringReplace = str_replace('":','",',$Stringtoreplace);
$NewStringReplace = str_replace(', "','],["',$NewStringReplace);

//If you want to change every double quotes to single remove line below
//$NewStringReplace = str_replace('"',"'",$NewStringReplace);

echo $NewStringReplace;
// echo : [ "Aluno1", 65.8],["Aluno2", 0.3],["Aluno3", 34.9 ]

答案 3 :(得分:-1)

好的,谢谢你们。我通过使用以下代码得到它:

$old_sentence = "[ "Aluno1": 65.8, "Aluno2": 0.3, "Aluno3": 34.9 ]";
$new_sentence = str_replace(',', '],[', $old_sentence);
$output = str_replace(':', ',', $new_sentence);
echo $output;