2010-11-17 134 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

相关问题