2010-11-17 139 views
1

我將如何最好地實現以下內容:如何僅替換字符串的未加引號的部分?

我想在PHP中找到並替換字符串中的值,除非它們使用單​​引號或雙引號。

EG。

$string = 'The quoted words I would like to replace unless they are "part of a quoted string" '; 

$terms = array(
    'quoted' => 'replaced' 
); 

$find = array_keys($terms); 
$replace = array_values($terms);  
$content = str_replace($find, $replace, $string); 

echo $string; 

echo「d字符串應該返回:

'The replaced words I would like to replace unless they are "part of a quoted string" ' 

在此先感謝您的幫助。

回答

1

您可以將字符串拆分爲帶引號或不帶引號的部分,然後僅在未加引號的部分調用str_replace。下面是一個使用preg_split的示例:

$string = 'The quoted words I would like to replace unless they are "part of a quoted string" '; 
$parts = preg_split('/("[^"]*"|\'[^\']*\')/', $string, -1, PREG_SPLIT_DELIM_CAPTURE); 
for ($i = 0, $n = count($parts); $i < $n; $i += 2) { 
    $parts[$i] = str_replace(array_keys($terms), $terms, $parts[$i]); 
} 
$string = implode('', $parts); 
+0

謝謝,工作起來就像一個魅力。非常感謝贊助:) – Chris 2010-11-17 22:11:29

相關問題