0

this string is lastupdate BETWEEN @DAY and @DAY.I want to replace 2 @DAY with 11/15/2017 09:45 and 11/28/2017 12:23 by sequence

Expect Result => lastupdate BETWEEN 11/28/2017 12:23 and 11/28/2017 12:23

I used some code about this

$value_cond[0] => 11/15/2017 09:45 
$value_cond[1] => 11/28/2017 12:23


$tmp_o[1] = 'lastupdate BETWEEN @DAY and @DAY';     
$first = strpos($tmp_o[1],'@',0);//find @ first position
$output = substr_replace($tmp_o[1],$value_cond[0],$first);
$secound = strpos($tmp_o[1],'@',$first+1);//find @ next position
$output .= substr_replace($tmp_o[1],$value_cond[1],$secound);
    dump($output);die();

and result from my code is

lastupdate BETWEEN 11/15/2017 09:45lastupdate BETWEEN @DAY and 11/28/2017 12:23

Please Help ,Thanks

4 Answers 4

2

You can use sprintf function in php.

<?php
$value_cond[0] => 11/15/2017 09:45;
$value_cond[1] => 11/28/2017 12:23;
$txt = sprintf("lastupdate BETWEEN %s and %s.",$value_cond[0],$value_cond[1]);
echo $txt;
?>
Sign up to request clarification or add additional context in comments.

1 Comment

%u It will display only integer. I will use %s.
1

You can use preg_replace and set the $limit variable.

$str = "lastupdate BETWEEN @DAY and @DAY";

$value_cond[0] = "11/15/2017 09:45";
$value_cond[1] = "11/28/2017 12:23";

$limit =1;
Foreach($value_cond as $val){
     $str =  preg_replace("/@DAY/", $val, $str, $limit);
}

Echo $str;

https://3v4l.org/p2T0f

The $limit means preg_replace only makes x replacements at the time.
So looping the array and replacing with array value and limit set to 1 means it will replace the first @DAY with the first value of the array.

1 Comment

Many Thanks!! and It's look like efficiency.
1

You can use preg_replace_callback function

echo preg_replace_callback('/@DAY/i', 
        function($i) use (&$value_cond) {
        return array_shift($value_cond);
        }, $tmp_o[1]);
// lastupdate BETWEEN 11/15/2017 09:45 and 11/28/2017 12:23

Comments

1

Please note that this approach will work for php5.6 and greater because of using '...$value_cond'

    <?php

    $original_str = 'lastupdate BETWEEN @DAY and @DAY';

    $value_cond[0] = '11/15/2017 09:45'; 
    $value_cond[1] = '11/28/2017 12:23';

    $tmp_str = str_replace('@DAY', '%s', $original_str);

    $result_string = sprintf($tmp_str, ...$value_cond);

    echo $result_string; // lastupdate BETWEEN 11/15/2017 09:45 and 11/28/2017 12:23

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.