[英]php preg_replace expression
我需要一個用於PHP preg_replace的表達式,因此僅對沒有PHP數組的“ [”和“]”替換為“(”和“)”即可。 請閱讀問題並仔細查看示例...
謝謝...
樣品:
// input
$foo[];
bar["name"];
// output
$foo[];
bar("name");
我不知道“ 僅針對無PHP數組 ”的含義,但是如果您只是替換單個字符,為什么要使用preg? str_replace()
應該可以正常工作。
[ghoti@pc ~]$ cat doit
#!/usr/local/bin/php
<?php
$text="a[b]c\n";
$in = array( "[", "]" );
$out = array( "(", ")" );
print str_replace($in, $out, $text);
[ghoti@pc ~]$ ./doit
a(b)c
[ghoti@pc ~]$
preg_replace(array("/\[/", "/\]/"),array("(", ")"), $content);
這就是您最簡單的將[用(和]替換為)的方法。 除非您的事情有些復雜?
這應該做(棘手的部分是將變量與其他內容區分開):
^(.*[,;\?:/"'\(\)\[\]-+={}#@*^ ~&!%]+)*\[([^\]]*)\](.*)
| 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]
希望這會有所幫助(並且能起作用^^)
我對正則表達式不太擅長,因此在偽代碼中,您需要使用:
[whitespace] then [Any alpha numeric] then [square brace] then [double quote] then [record the value]
then [double quote] then [square brace]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.