php preg_replace表达式

时间:2012-04-03 04:53:32

标签: php preg-replace

我需要一个PHP preg_replace的表达式,所以只需将“[”和“]”替换为“(”和“)”仅适用于没有PHP数组。 请仔细阅读问题并仔细查看示例......

谢谢...

样品:

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

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

4 个答案:

答案 0 :(得分:0)

我不知道“仅适用于没有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 ~]$ 

答案 1 :(得分:0)

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

这是你能做的最简单的替换[with(和)with)。除非你的事情稍微复杂一些?

答案 2 :(得分: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]

希望这有帮助(并且有效^^)

答案 3 :(得分:0)

我对正则表达式并不擅长,所以在伪代码中你需要的是拾取:

[whitespace] then [Any alpha numeric] then [square brace] then [double quote] then [record the value]
then [double quote] then [square brace]
相关问题