简体   繁体   English

PHP preg_replace表达式

[英]php preg_replace expression

I need an expression for PHP preg_replace so just replace "[" and "]" with "(" and ")" only for none PHP arrays. 我需要一个用于PHP preg_replace的表达式,因此仅对没有PHP数组的“ [”和“]”替换为“(”和“)”即可。 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? 我不知道“ 仅针对无PHP数组 ”的含义,但是如果您只是替换单个字符,为什么要使用preg? str_replace() should work just fine. 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);

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 1:确保它不是PHP变量

2: the opening bracket 2:开括号

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) 3:方括号内的内容(如果有嵌套的方括号,则可能是个问题,例如,如果您必须执行mustMatch[$mustNotMatch[somekey]] ,则可能会以mustMatch($mustNotMatch[somekey)] ,这很奇怪并且可能需要处理)

4: the closing bracket 4:右括号

5: whatever is after the brackets 5:括号后面是什么

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM