patipat chewprecha
patipat chewprecha

Reputation: 285

PHP - Replace 2 string on 2 position in a string

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

Upvotes: 0

Views: 68

Answers (4)

Chanaka Karunarathne
Chanaka Karunarathne

Reputation: 2046

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

Upvotes: 2

Oleksandr Zaitsev
Oleksandr Zaitsev

Reputation: 46

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

Upvotes: 1

Andreas
Andreas

Reputation: 23958

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.

Upvotes: 1

splash58
splash58

Reputation: 26153

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

Upvotes: 1

Related Questions