2012-04-03 46 views
0

我需要一個PHP preg_replace的表達式,所以只需將「[」和「]」替換爲「(」和「)」僅適用於任何PHP數組。 請閱讀問題,仔細看樣品...php preg_replace表達式

謝謝...

樣品:

// input 
$foo[]; 
bar["name"]; 

// output 
$foo[]; 
bar("name"); 

回答

0

我不知道什麼是 「只爲沒有PHP陣列」的意思,但如果你只是更換個人角色,爲什麼要用preg? str_replace()應該可以正常工作。

[[email protected] ~]$ cat doit 
#!/usr/local/bin/php 
<?php 

$text="a[b]c\n"; 

$in = array("[", "]"); 
$out = array("(", ")"); 

print str_replace($in, $out, $text); 

[[email protected] ~]$ ./doit 
a(b)c 
[[email protected] ~]$ 
+0

這也將取代OP的問題$ foo的 – 2012-04-03 05:03:42

+0

的問題是不明確;是'$ foo []'包含要替換的東西的變量,還是應該免除翻譯的東西?我明白你是如何解釋它的,但更好的清晰度會更好。 – ghoti 2012-04-03 05:06:06

0
preg_replace(array("/\[/", "/\]/"),array("(", ")"), $content); 

那你可以做,以取代簡單的[與(和]用)。除非你的事情稍微複雜一點?

+0

請仔細閱讀該問題並仔細閱讀樣本... – 2012-04-03 05:09:16

+0

您的問題根本不清楚 – DdD 2012-04-03 07:13:59

0

這應該做(棘手的問題是,以區別於其他的東西變量):

^(.*[,;\?:/"'\(\)\[\]-+={}#@*^ ~&!%]+)*\[([^\]]*)\](.*) 
|     1     |2| 3 |4| 5| 
(before)[(inside)](after) 

1:確保它不是一個PHP變量

2:開括號

3 :括號內有什麼(如果有嵌套括號,這可能是一個問題,就像你做mustMatch[$mustNotMatch[somekey]],你可能最終會得到mustMatch($mustNotMatch[somekey)],這很奇怪,如果需要可以處理)

4:右括號

5:無論是在括號後

所以這應該(未測試^^)匹配在下列情況下的圖案:

bar[] > bar() 
bar[foo] > bar(foo) 
a+bar["foo"] > a+bar("foo") 
@foo[bar] > @foo(bar) 
a+$foo[bar[foo]]*bar[foo] > a+$foo[bar(foo)]*bar(foo) 
this is a $foo[bar] with a [bar] > this is a $foo[bar] with a (bar) 

,它應該在下列情況下不匹配:

$foo[] 
$foo[bar] 
a-$foo[bar] 
@$foo[bar] 

希望這有助於(和工作^^)

0

我在正則表達式不是很大所以在僞代碼,你需要的是皮卡:

[whitespace] then [Any alpha numeric] then [square brace] then [double quote] then [record the value] 
then [double quote] then [square brace]