替换方括号php中所有匹配数字的子字符串


replace all substring matching numbers in square brackets -php

这可能很容易,但我做不到。

给定字符串:

$str="i have an apple[1], and another one [2], and another[3]";

我想更换[1][2]。。带<tag id=1> <tag id=2>

我试过$str2 = preg_replace('/[([1-9][0-9]*)]/', '<tag id=1>', $str);

但不能插入变量进行

$str2 = preg_replace('/[([1-9][0-9]*)]/', '<tag id=$var>', $str);

我使用的正则表达式也是一个问题,它适用于某些情况,但不适用于某些:(

我们非常感谢您的帮助。。

编辑:正如@m42和@scibuff所指出的,有效的正则表达式是:/'[([1-9][0-9]*)']/

但如何为每次更换增加?

编辑2:我误解了M42的答案,谢谢。

但如果我有另一根绳子呢;

str2="i have an egg [4], and another egg [5]";

如何继续第一个preg_replace开始的增量?

我的意思是,想要的结果是:

i have an apple <tag id=1>,... i have an egg [4]..

第3版:由M42解决-事实上,问题的第二部分毫无意义,preg_replace将不断增加。。谢谢大家!!

怎么样:

$str2 = preg_replace('/'[([1-9][0-9]*)']/', "<tag id=$1>", $str);

这里有一个测试:

$arr = array(
    "I have an apple[1], and another one [2], and another[3]",
    "i have an egg [4], and another egg [5]",
);
foreach ($arr as $str) {
    echo "before: $str'n";
    $str = preg_replace('/'[([1-9]'d*)']/', "<tag id=$1>", $str);
    echo "after : $str'n";
}

输出:

before: I have an apple[1], and another one [2], and another[3]
after : I have an apple<tag id=1>, and another one <tag id=2>, and another<tag id=3>
before: i have an egg [4], and another egg [5]
after : i have an egg <tag id=4>, and another egg <tag id=5>
        $str="i have an apple[1], and another one [2], and another[3]";
        preg_match_All("/'[[0-9]+']/",$str,$matches);
        $replace=array();
        for($j=0;$j<count($matches[0]);$j++)
        {
         $replace[]=htmlspecialchars("<tag id=$j>");
        }
         for($i=0;$i<count($matches[0]);$i++)
        {
        for($j=0;$j<count($matches[0]);$j++)
        {
        if($i==$j)
        {
         $str=(str_replace($matches[0][$i],$replace[$j],$str));
        }
        }
        }
        echo $str;