您可以使用 preg_match_all() 查找出现次数,使用此数组查找数据库中的值,然后使用 str_replace 替换之后的每个值。
首先,您需要获取所有事件:
preg_match_all('/{(.*?)}/', $string, $matches, PREG_PATTERN_ORDER);
匹配数组将如下所示:
Array
(
[0] => Array
(
[0] => {}
[1] => {25}
[2] => {FIELD_CONTRACTTEXT}
)
[1] => Array
(
[0] =>
[1] => 25
[2] => FIELD_CONTRACTTEXT
)
)
然后,您可以循环遍历数组以查找需要替换的各个元素。
您可以使用以下内容检查数据库,然后替换值:
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