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

8

我可以得到一个字符串:

   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


你不能在str_replace中使用正则表达式,但是你可以在preg_replace中使用。 - sachleen
然后使用 array_keys() 并遍历它们? - demonking
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

你可以使用 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";
    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
$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.的答案(并将搜索字符串替换为<%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';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接