0

I have a pixel like:

<img src='http://www.montag.com/directory_folder/tracking_noip.php?tracking=[ID_MTG]&data=[TEL]' height='1' width='1' border='0'/>

I need to replace the keys [TEL] and [ID_MTG] with the value I receive from a script. For example if I have:

$tel = "0613321223";
$id_mtg = "4875";
$email = "[email protected]";

I need to output:

<img src='http://www.montag.com/directory_folder/tracking_noip.php?tracking=4875&data=0613321223' height='1' width='1' border='0'/>

If I have:

<img src='http://www.montag.com/directory_folder/tracking_noip.php?tracking=[ID_MTG]&data=[EMAIL]' height='1' width='1' border='0'/>

I need to ouput:

<img src='http://www.montag.com/directory_folder/tracking_noip.php?tracking=4875&[email protected]' height='1' width='1' border='0'/>

I have:

$tel = "0613357221";
$email = "[email protected]";
$id_mtg = "560";

$string = "<img src='http://www.montag.com/directory_folder/tracking_noip.php?tracking=[TEL]&data=[ID_MTG]' height='1' width='1' border='0'/>";
$patterns = array();
$patterns[0] = ' /\[TEL\]/ ';
$patterns[1] = ' /\[EMAIL\]/ ';
$patterns[2] = ' /\[ID_MTG\]/ ';
$replacements = array();
$replacements[2] = $id_mtg;
$replacements[1] = $email;
$replacements[0] = $tel;
echo htmlentities(preg_replace($patterns, $replacements, $string));

But my string is:

<img src='http://www.montag.com/directory_folder/tracking_noip.php?tracking=520&data=0613357221' height='1' width='1' border='0'/>

The order is reversed.

1
  • I don't see the need for regular expressions if you search for fixed strings. Have you tried strtr? Commented Apr 10, 2017 at 16:39

2 Answers 2

3
$str = 'hi all, I said hello';

$replace_pairs = array(
  'all' => 'everybody',
  'hello' => 'hey',
);

echo strtr($str, $replace_pairs);

This would help you.

Sign up to request clarification or add additional context in comments.

Comments

1

The order is wrong because you defined your $replacements in reverse order. Even though you specified indexes in descending order, the order in which you created the array is preserved. Check this with print_r($replacements);. You could sort by keys with ksort() if needed to get the array in the proper order.

But for this application, strtr() or str_replace() makes more sense. Make sure to define the arrays in the same order:

$search  = array('[TEL]', '[EMAIL]', '[ID_MTG]');
$replace = array($tel, $email, $id_mtg);

$result = str_replace($search, $replace, $string);

1 Comment

I look at this solution after the train but it seems to me perfectly do the trick! I think i search too far ^^

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.