I need an expression for PHP preg_replace so just replace "[" and "]" with "(" and ")" only for none PHP arrays. Please read the question and see the sample carefully...
Thank you...
Sample:
// input
$foo[];
bar["name"];
// output
$foo[];
bar("name");
I don't know what " only for none PHP arrays " means, but if you're just replacing individual characters, why use a preg? str_replace()
should work just fine.
[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);
Thats the simplest you can do to replace [ with ( and ] with ). Unless your after something a bit more complex?
This should do (the tricky part is to differentiate variables from other stuff):
^(.*[,;\?:/"'\(\)\[\]-+={}#@*^ ~&!%]+)*\[([^\]]*)\](.*)
| 1 |2| 3 |4| 5|
(before)[(inside)](after)
1: makes sure it's not a PHP variable
2: the opening bracket
3: what's inside the brackets (it might be an issue if there are nested brackets, like if you do mustMatch[$mustNotMatch[somekey]]
, you'll probably end up with mustMatch($mustNotMatch[somekey)]
, which is weird and can probably be dealt with if you need to)
4: the closing bracket
5: whatever is after the brackets
So this should (not tested ^^) match the pattern in the following cases:
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)
And it should not match in the following cases:
$foo[]
$foo[bar]
a-$foo[bar]
@$foo[bar]
Hope this helps (and works ^^)
I'm not great at regular expressions so in pseudocode what you need is to pickup:
[whitespace] then [Any alpha numeric] then [square brace] then [double quote] then [record the value]
then [double quote] then [square brace]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.