i’m using preg replace to replace syntax in my output. Here is my code:
$input_val_Arr = array("ic"=>'8808295663',
"promocodereply"=>'123456',
"phone"=>'017123456789');
foreach($input_result as $row)
{
//eg of $row->input_title is promocodereply, phone, ic
$special_key = $row->input_title;
$rule = "/<".$row->input_title.">/i";
//if(preg_match('/promocodereply/i', $success_msg))
if(preg_match($rule, $success_msg))
{
if(isset($input_val_Arr[$special_key]))
{
//$success_msg = preg_replace('/<promocodereply>/i', '123456', $success_msg);
$success_msg = preg_replace($rule, $input_val_Arr[$special_key], $success_msg);
}
}
}
var_dump($success_msg);
The $success_msg content is Success! <PROMOCODEREPLY> <PHONE> <IC>
So the var_dump output should be Success! 123456 017123456789 8808295663
However the ic syntax is not replace and this is what i get. Success! 123456 017123456789 <IC>
What is the problem here? Thanks.
The regex is fine. Your
$input_resultarray however contains only an entry where$row->input_title==is"IC"or something. Ths will work with the regex, but fail theisset($input_val_Arr[$special_key]). Since that’s not a case-insensitive check.You need to clean up your whole approach. The multiple checks are awfully redundant, and the variable names suck. A single
preg_replace_callbackis advisable for this task, with just/<(IC|PROMOCODEREPLY|PHONE)>/ias regex. Or use a singlepreg_replacecall with arrays as subject and replacement.