简体   繁体   中英

Replace only (case insensitive) whole word from string php

    $replace = array
        (
            [$name] => John
            [$date] => Aug 17,2020
            [$timezone] => US/Eastern
            [$time] => 23:00
            [$datetime] => Aug 17,2020 23:00
            [$tz] => EDT
            [$dateformat("m/d/y h:i:A")] => 08/17/20 11:00:PM
        )

$message = "This is test Message with $dateformat(\"m/d/y h:i:A\")  & \"Hello\"\n& This test Message again with $tzs";

I have above array and string, now I want to replace array keys with array values in given string.

I have tried below code,

$final_msg = str_ireplace(array_keys($replace), array_values($replace), $message);


       

Above code gives me below result:

This is test Message Aug 17,2020format("m/d/yh:i:A") & "Hello" & This test MEssage EDTs $rec

Now issue is that, $dateformat(\"m/d/yh:i:A\") should be replace with "08/17/20 11:00:PM", but it does not check for whole world and only $date is replaced Aug 17,2020.

So I want to only whole matched word from message and word can be case insensitive.

Can anyone please help me?

#1: You could use the following code, which replace word by word. So I must change m/d/yh:i:A to m/d/yh:i:A. But it work:D

$replace = array (
        '$name' => "John",
        '$date' => "Aug 17,2020",
        '$timezone' => "US/Eastern",
        '$time' => "23:00",
        '$datetime' => "Aug 17,2020 23:00",
        '$tz' => "EDT",
        '$dateformat("m/d/y-h:i:A")' => "08/17/20 11:00:PM"
);

$message = "This is test Message with \$dateformat(\"m/d/y-h:i:A\")  & \"Hello\"\n& This test Message again with \$tz";
$message_array = explode ( " ", $message );
foreach ( $message_array as $key => $element ) {
    foreach ( $replace as $search_str => $replace_str ) {
        if ($element == $search_str)
            $message_array [$key] = $replace_str;
    }
}

$final_msg = implode ( " ", $message_array );
echo $final_msg;

#2

uksort($replace , function($a, $b) {
   return strlen($a) - strlen($b);
});

that will sort $replace by keylength, avoid you to replace shorter string before long string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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