2014-08-29 110 views
0

我有一個PHP數組是這樣的:如何使用PHP的preg_replace替換

$_0xb29b = ['item1','item2','item3']; 

而且我有這樣

_0xb29b[0] foo foo foo foo foo foo _0xb29b[2] 

你們可以告訴我一個文本文件,如何更換_0xb29b[0]在文本文件中的數組中正確的項目?我想文壽是這樣的:

item1 foo foo foo foo foo foo item3 

回答

2

使用preg_replace_callback()

<?php 
// header('Content-Type: text/plain; charset=utf-8'); 

$str  = '_0xb29b[0] foo foo foo foo foo foo _0xb29b[2], _0xb29b[xxx]'; 
$_0xb29b = ['item1','item2','item3', 'xxx' => 5]; 

$result = preg_replace_callback(
    '/\_0xb29b\[([^\]]+)\]/', 
    function($matches)use($_0xb29b){ 
     return $_0xb29b[$matches[1]]; 
    }, 
    $str 
); 

echo $result; 
?> 

表演:

item1 foo foo foo foo foo foo item3, 5 

注:要獲得文件內容作爲字符串我建議您閱讀file_get_contents()手冊。

+0

@NguyễnĐăngKhoa你可以添加一個例子嗎? – BlitZ 2014-08-29 06:56:17

+0

當它不僅是數字而且還有像_0xb29b [文本]這樣的文本並且代碼中有正確的元素時呢? – thangngoc89 2014-08-29 06:58:13

+0

請看我的回答。感謝您的幫助 – thangngoc89 2014-08-29 07:01:28

0

我花了太多的時間讓這個工作不發佈。不使用preg_match,但幾乎複製它。首先它從變量名稱創建針。然後,使用substr_count和strpos在乾草堆中搜索針。然後使用找到的針的位置和針的長度來獲取變量的索引,並使用用於創建針的變量數組進行替換。鏈接到底部的所有來源。

<?php 

function print_var_name($var) { 
    foreach($GLOBALS as $var_name => $value) { 
     if ($value === $var) { 
      return $var_name; 
     } 
    } 
    return false; 
} 

$_0xb29b = array('item1','item2','item3'); 

$needle = print_var_name($_0xb29b); 
$needle_length = strlen($needle); 
$haystack = '_0xb29b[0] foo foo foo foo foo foo _0xb29b[2]'; 
$haystack_height = strlen($haystack); 

$num_needles = substr_count($haystack,$needle) . '<br />'; 
if($num_needles>0){ 
    $offset = 0; 
    for($i=0;$i<$num_needles;$i++){ 
     $needle_pos[$i] = strpos($haystack,$needle,$offset); 
     $needle_index[$i] = substr($haystack,$needle_pos[$i]+$needle_length+1,1); 
     if($needle_pos[$i]+$needle_length+3<$haystack_height){ 
      $haystack = substr($haystack,0,$needle_pos[$i]). ' ' .${$needle}[$needle_index[$i]] . ' ' . substr($haystack,$needle_pos[$i]+$needle_length+3); 
     } else { 
      $haystack = substr($haystack,0,$needle_pos[$i]). ' ' .${$needle}[$needle_index[$i]]; 
     } 
     $offset = $needle_pos[$i]+1; 
    } 
} 
echo $haystack; 
?> 

[變量變量] [1]用於轉動字符串返回到一個變量與所述變量爲一個陣列,並使用

${$needle}[index] 

調用數組索引的問題。
http://php.net/manual/en/language.variables.variable.php
http://php.net/manual/en/function.substr.php
http://php.net/manual/en/function.strpos.php
http://php.net/manual/en/function.substr-count.php
How to get a variable name as a string in PHP?

+0

我看到這是一個非常好的方法。我瞭解你的方法:) – thangngoc89 2014-08-29 14:15:00