簡體   English   中英

PHP用數組中的值替換字符串

[英]PHP replace string with values from array

我有一個字符串,如:

   Hello <%First Name%> <%Last Name%> welcome

我有一個數組

 [0] => Array
    (
        [First Name] => John
        [Last Name] => Smith
    )

我需要做的是取字符串並將<%中的單詞替換為數組中的實際文本

所以我的輸出將是

   Hello John Smith welcome

我不知道如何實現這一目標,但我似乎無法用常規文本替換它

$test = str_replace("<%.*%>","test",$textData['text']);

對不起,我應該提到數組鍵可能會與<%First Name%>

所以它甚至可以是<%city%> ,數組可以是city=>New York

$array = array('<%First Name%>' => 'John', '<%Last Name%>' => 'Smith');
$result = str_replace(array_keys($array), array_values($array), $textData['text']);

您可以在str_replace中使用數組搜索和替換變量

$search = array('first_name', 'last_name');
$replace = array('John', 'Smith');

$result = str_replace($search, $replace, $string);
$string = "Hello <%First Name%> <%Last Name%> welcome";
$matches = array(
    'First Name' => 'John',
    'Last Name' => 'Smith'
);

$result = preg_replace_callback('/<%(.*?)%>/', function ($preg) use ($matches) { return isset($matches[$preg[1]]) ? $matches[$preg[1]] : $preg[0]; }, $string);            

echo $result;
// Hello John Smith welcome

你可以用這個:

$result = preg_replace_callback('~<%(First|Last) Name)%>~', function ($m) {
    return $yourarray[$m[1] . ' Name']; } ,$str);

或者非常簡單(可能更有效),使用Brian H.回答(並用<%First Name%><%Last Name%>替換搜索字符串)。

你可以使用str_replace

$replacedKeys = array('<%First Name%>','<%Last Name%>');

$values = array('John','Smith');

$result = str_replace($replacedKeys,$values,$textData['text']);

你能試試嗎

    $string ="Hello <%First Name%> <%Last Name%> welcome";
    preg_match_all('~<%(.*?)%>~s',$string,$datas);
    $Array = array('0' => array ('First Name' => 'John', 'Last Name' => 'Smith' ));
    $Html =$string;
    foreach($datas[1] as $value){           
        $Html =str_replace($value, $Array[0][$value], $Html);
    }
    echo str_replace(array("<%","%>"),'',$Html);
echo ' Hello '.$array[0][First Name].' '.$array[0][Last Name].'  welcome';
function temp_tag_replace($tag_start,$tag_end,$temp_array,$text){
      if(is_array($temp_array)){
      $keys=array_keys($temp_array);
        foreach ( $keys as $key){
        $val=$temp_array[$key];
        $key=$tag_start.$key.$tag_end;
        $text=str_replace($key,$val,$text);
        }
      }
      return $text;
    }

    $text='Hi %*Name*% %*Surname*%';
    $temp_array=array('Name'=>'Otto','Surname'=>'Man');
    $tag_start='%*';
    $tag_end='*%';

    echo temp_tag_replace($tag_start,$tag_end,$temp_array,$text);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM