PHP 用数组中的值替换字符串

问题描述 投票:0回答:8

我有一个字符串,例如:

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

我有一个数组

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

我需要做的是获取字符串并替换<% with the actual text from the array

中的单词

所以我的输出是

   Hello John Smith welcome

我不确定如何做到这一点,但我什至无法用常规文本替换它

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

对不起,我应该提到数组键可能会有所不同以及

<%First Name%>

所以它甚至可以是

<%city%>
并且数组可以是
city=>New York

php regex preg-replace preg-match str-replace
8个回答
24
投票
$array = array('<%First Name%>' => 'John', '<%Last Name%>' => 'Smith');
$result = str_replace(array_keys($array), array_values($array), $textData['text']);

6
投票

您可以使用数组来搜索和替换 str_replace 中的变量

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

$result = str_replace($search, $replace, $string);

2
投票

你能试试这个吗,

    $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);

2
投票

你可以使用

str_replace

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

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

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

2
投票
$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

1
投票

你可以使用这个:

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

或者更简单(可能更有效),使用 Brian H. answer(并用

<%First Name%>
<%Last Name%>
替换搜索字符串)。


1
投票
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);

0
投票
echo ' Hello '.$array[0][First Name].' '.$array[0][Last Name].'  welcome';
© www.soinside.com 2019 - 2024. All rights reserved.