简体   繁体   English

PHP用变量替换字符串内的字符

[英]PHP Replacing Character Inside String With Variable

In few words, I am trying to replace all the "?" 简而言之,我正在尝试替换所有的“?” with the value inside a variable and it doesn't work. 值包含在变量中,它将不起作用。 Please help. 请帮忙。

    $string = "? are red ? are blue";
    $count = 1;

    update_query($string, array($v = 'violets', $r = 'roses'));


    function update_query($string, $values){

        foreach ( $values as $val ){

            str_replace('?', $val, $string, $count);    
        }

        echo $string;
    }

The output I am getting is: ? 我得到的输出是: are red ? 是红色的 ? are blue 是蓝色的

Frustrated by people not paying attention, I am compelled to answer the question properly . 由于人们不注意而感到沮丧,我不得不正确地回答这个问题。

str_replace will replace ALL instances of the search string. str_replace将替换搜索字符串的所有实例。 So after violets , there will be nothing left for roses to replace. 因此,在violets之后,就没有什么可以代替的roses了。

Sadly str_replace does not come with a limit parameter, but preg_replace does. 可悲的是, str_replace没有限制参数,但是preg_replace却没有。 But you can actually do better still with preg_replace_callback , like so: 但是实际上,您可以使用preg_replace_callback更好地做到,就像这样:

function update_query($string, $values){
    $result = preg_replace_callback('/\?/', function($_) use (&$values) {
        return array_shift($values);
    }, $string);
    echo $string;
}

您忘记将其设置为等于变量。

$string = str_replace('?', $val, $string, $count); 

You probably want to capture the return from str_replace in a new string and echo it for each replacement, and pass $count by reference. 您可能想在新字符串中捕获来自str_replace的返回值,并在每次替换时回显它,并按引用传递$ count。

   foreach ( $values as $val ){

        $newString = str_replace('?', $val, $string, &$count);    
        echo $newString;
   }

This is the best and cleanest way to do it 这是最好,最干净的方法

  <?php

  $string = "? are red ? are blue";
  $string = str_replace('?','%s', $string);
  $data = array('violets','roses');

  $string = vsprintf($string, $data);  

  echo $string;

Your code edited 您的代码已编辑

$string = "? are red ? are blue";

update_query($string, array('violets','roses'));


function update_query($string, $values){

  $string = str_replace('?','%s', $string);
  $string = vsprintf($string, $values);

    echo $string;
}

Ok guys here is the solution from a combination of some good posts. 好的,这里是一些好帖子的综合解决方案。

$string = "? are red ? are blue";

update_query($string, array($v = 'violets', $r = 'roses'));

function update_query($string, $values){

    foreach ( $values as $val ){

        $string = preg_replace('/\?/', $val, $string, 1);

    }

    echo $string;
}

As mentioned, preg_replace will allow limiting the amount of matches to update. 如前所述, preg_replace将允许限制要更新的匹配项的数量。 Thank you all. 谢谢你们。

You can solve this in two ways: 您可以通过两种方式解决此问题:

1) Substitute the question marks with their respective values. 1)将问号替换为其各自的值。 There are a hundred ways one could tackle it, but for something like this I prefer just doing it the old-fashioned way: Find the question marks and replace them with the new values one by one. 有一百种方法可以解决这个问题,但是对于这样的事情,我宁愿只用老式的方法来解决:找到问号,然后用新的值一一替换。 If the values in $arr contain question marks themselves then they will be ignored. 如果$arr的值本身包含问号,则将忽略它们。

function update_query($str, array $arr) {
    $offset = 0;
    foreach ($arr as $newVal) {
        $mark = strpos($str, '?', $offset);
        if ($mark !== false) {
            $str = substr($str, 0, $mark).$newVal.substr($str, $mark+1);
            $offset = $mark + (strlen($newVal) - 1);
        }
    }
    return $str;
}
$string = "? are red ? are blue";
$vars = array('violets', 'roses');
echo update_query($string, $vars);

2) Or you can make it easy on yourself and use unique identifiers. 2)或者,您可以自己轻松使用唯一标识符。 This makes your code easier to understand, and more predictable and robust. 这使您的代码更易于理解,并且更具可预测性和鲁棒性。

function update_query($str, array $arr) {
    return strtr($str, $arr);
}
echo update_query(':flower1 are red :flower2 are blue', array(
    ':flower1' => 'violets',
    ':flower2' => 'roses',
));

You could even just use strtr() , but wrapping it in a function that you can more easily remember (and which makes sense in your code) will also work. 您甚至可以只使用strtr() ,但是将其包装在一个可以更容易记住的函数中(这在您的代码中很有意义)也将起作用。

Oh, and if you are planning on using this for creating an SQL query then you should reconsider. 哦, 如果您打算使用它来创建SQL查询,则应该重新考虑。 Use your database driver's prepared statements instead. 请改用数据库驱动程序的预处理语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM