teutara
teutara

Reputation: 635

replace all substring matching numbers in square brackets -php

it might be very easy but i could not do it..

given a string:

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

i want to replace [1], [2] .. with <tag id=1> <tag id=2>

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

but can not insert a variable to do

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

the regex i am using is also a problem, it works for some cases but does not for some :(

any help is deeply appreciated..

EDIT: as @m42 and @scibuff pointed out, valid regex would be: /\[([1-9][0-9]*)\]/

but how to increment for each replacement?

EDIT 2: i misunderstood M42's answer, thanks.

But what if i have another string;

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

how can i continue the increment started by first preg_replace?

i mean, desired result is:

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

EDIT 3: SOLVED by M42 -in fact second part of the question is meaningless, preg_replace will increment continously.. thanks all!!

Upvotes: 1

Views: 1132

Answers (2)

kal
kal

Reputation: 48

        $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;

Upvotes: 0

Toto
Toto

Reputation: 91488

How about:

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

Here is a test:

$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";
}

output:

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>

Upvotes: 2

Related Questions