1

I have the following string

"Enter Contarct Fields wherever you want and enclose it with {}.You can use field's id or field's fieldcode for example {25} or {FIELD_CONTRACTTEXT}"

I want to replace this {25} and {FIELD_CONTRACTTEXT} with their equivalent value from databse. Say 25 is a ID so I wanted to put name of the field of which 25 is the ID of.

There are many examples of replacing curly braces but no solution is there for replacing content like this. Please help me, I have tried many things.

PS: Please keep in mind that occurrence of {} is dynamic and 25 will not be a static number and there can be multiple {} in a string.

2
  • 3
    i have tried many things... please post them (or the most relevant/successful ones so far). What is it explicitly that you are having problems with? Commented Apr 16, 2012 at 15:00
  • Have a look at preg_replace_callback. Commented Apr 16, 2012 at 15:07

1 Answer 1

0

You can use preg_match_all() to find the occurrences, use this array to find the values in the database and then str_replace to replace each value after that.

To begin with you will need to fetch all the occurrences:

preg_match_all('/{(.*?)}/', $string, $matches, PREG_PATTERN_ORDER);

The matches array will look like this:

Array
(
    [0] => Array
        (
            [0] => {}
            [1] => {25}
            [2] => {FIELD_CONTRACTTEXT}
        )

    [1] => Array
        (
            [0] => 
            [1] => 25
            [2] => FIELD_CONTRACTTEXT
        )

)

You can then cylce through the array to find the individual elements that need to be replaced.

You can use the following to check the database and then replace values:

mysql_connect("localhost", "root", "");
mysql_select_db("data");

$string = "Enter Contarct Fields wherever you want and enclose it with {}.You can use field's id or field's fieldcode for example {25} or {FIELD_CONTRACTTEXT}";

preg_match_all('/{(.*?)}/', $string, $matches, PREG_PATTERN_ORDER);

foreach($matches[1] as $match) {
    $sql = mysql_query("SELECT * FROM table WHERE `element`='".addslashes($match)."'");
    if(mysql_num_rows($sql)==1){
        $row = mysql_fetch_assoc($sql);
        str_replace($string, "{".$match."}", $row['value']);
    }
}

echo $string; //echos final output with replaced values
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.