Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 正则表达式替换为->;,具体取决于条件_Php_Regex - Fatal编程技术网

Php 正则表达式替换为->;,具体取决于条件

Php 正则表达式替换为->;,具体取决于条件,php,regex,Php,Regex,我正在寻找一个正则表达式,它可以用“->”替换所有的“[”,但只有在它后面不跟“]”时 并同时将所有“]”替换为零,但仅当它们不在“[”旁边时 因此,换句话说,“test[hi][]”将变成“test->hi[]” 谢谢;) 我真的不知道该怎么做;)我假设括号中的内容如下(即字母、数字、下划线),并且您的代码是有效的(例如,no$test['five]) 这应处理: test[one] test['two'] test["three"] 但不是: test[$four] 这应该可以。它使用

我正在寻找一个正则表达式,它可以用“->”替换所有的“[”,但只有在它后面不跟“]”时

并同时将所有“]”替换为零,但仅当它们不在“[”旁边时

因此,换句话说,“test[hi][]”将变成“test->hi[]”

谢谢;)


我真的不知道该怎么做;)

我假设括号中的内容如下(即字母、数字、下划线),并且您的代码是有效的(例如,no
$test['five]

这应处理:

test[one]
test['two']
test["three"]
但不是:

test[$four]

这应该可以。它使用

\[     # match a [
(      # match group
[^\]]+ # match everything but a ] one or more times
)      # close match group 
\]     # match ] 
匹配括号之间的任何内容

$replaced = preg_replace("/\[([^\]]+)\]/", "->$1", $string);

将此正则表达式
\[(\w+)\]
替换为
->
+匹配组1

无需正则表达式

strtr($str, array('[]'=>'[]','['=>'->',']'=>''))




$ cat 1.php
<?php
echo strtr('[hi][]', array('[]'=>'[]','['=>'->',']'=>''));
$ php 1.php
->hi[]
strtrtr($str,数组('[]'=>'[]'、'['=>'->'、']]'=>'')
$cat 1.php

我认为他不需要匹配引号。+1表示不使用正则表达式。但需要注意的是,这只适用于这种特定格式(即
arr[key]
)。如果您有不同的键,您可能需要使用正则表达式。如果您可以在没有正则表达式的情况下解决任务,请不要使用正则表达式。干得好!
strtr($str, array('[]'=>'[]','['=>'->',']'=>''))




$ cat 1.php
<?php
echo strtr('[hi][]', array('[]'=>'[]','['=>'->',']'=>''));
$ php 1.php
->hi[]