0

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

3
  • 2
    How is it not working; define what errors you may be getting. Commented Dec 5, 2014 at 22:08
  • @Fred-ii- Not working meaning, no errors and the output is ? are red ? are blue Commented Dec 5, 2014 at 22:09
  • You're not assigning the str_replace result anywhere. Also research preg_replace_callback instead. Commented Dec 5, 2014 at 22:10

6 Answers 6

2

Frustrated by people not paying attention, I am compelled to answer the question properly.

str_replace will replace ALL instances of the search string. So after violets, there will be nothing left for roses to replace.

Sadly str_replace does not come with a limit parameter, but preg_replace does. But you can actually do better still with preg_replace_callback, like so:

function update_query($string, $values){
    $result = preg_replace_callback('/\?/', function($_) use (&$values) {
        return array_shift($values);
    }, $string);
    echo $string;
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you but this seem overly complex and str_replace does have a fourth parameter which limits the replacements, from PHP's Docs: " count If passed, this will be set to the number of replacements performed."
Read it again, @user3704920. It is SET to the number PERFORMED. It is NOT a "limit" parameter.
0

You forgot to set it equal to your variable.

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

1 Comment

@dmikester1 even if I declare count inside the function, it still doesn't work.
0

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.

   foreach ( $values as $val ){

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

Comments

0

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

Comments

0

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. Thank you all.

Comments

0

You can solve this in two ways:

1) Substitute the question marks with their respective values. 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.

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. 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.

Oh, and if you are planning on using this for creating an SQL query then you should reconsider. Use your database driver's prepared statements instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.