PHP str_replace [英] PHP str_replace

查看:42
本文介绍了PHP str_replace的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串 $var,我需要在其中替换一些文本.第一个X"需要替换为A",第二个X"需要替换为B,依此类推,示例如下:

I have the string $var in which I need to replace some text. The first "X" needs to be replaced by "A", the second "X" needs to be replaced by B and so on, here is an example:

<?php
$var = "X X X X"; // input
...
echo $var //the result: "A B C D"
?>

我尝试使用 str_replace 但这不起作用.

I tried with str_replace but that doesn't work.

谢谢

推荐答案

你可以使用 preg_replacelimit 参数只替换一次.

You could use preg_replace's limit argument to only replace once.

<?php
    $var = 'X X X X';
    $replace = array('A', 'B', 'C', 'D');
    foreach($replace as $r)
        $var = preg_replace('/X/', $r, $var, 1);
    echo $var;
?>

http://codepad.viper-7.com/ra9ulA

这篇关于PHP str_replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆