2014-01-13 78 views
3

替換字符串我有一個字符串,如:PHP和值從陣列

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

+0

你不能做str_replace函數的正則表達式,但你可以在preg_replace函數 – sachleen

+0

然後使用'array_keys()'並遍歷它們? – demonking

回答

1

你可以試試這個,

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

您可以使用數組兩個搜索和str_replace函數替換變量

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

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

您可以使用此:

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

或簡單得多(而且可能更有效),使用布賴恩·H.答案(由<%First Name%><%Last Name%>替換搜索字符串)。

1

你可以使用str_replace

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

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

$result = str_replace($replacedKeys,$values,$textData['text']); 
0
echo ' Hello '.$array[0][First Name].' '.$array[0][Last Name].' welcome'; 
10
$array = array('<%First Name%>' => 'John', '<%Last Name%>' => 'Smith'); 
$result = str_replace(array_keys($array), array_values($array), $textData['text']); 
+0

這個作品謝謝你 – Yeak

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