Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sksighna's avatar

asd

Ss

0 likes
4 replies
MichalOravec's avatar
$trans = [
    'Jack' => '<a href="http://www.jack.com">Jack</a>',
    'Jill' => '<a href="http://www.jill.com">Jill</a>',
    'Romeo' => '<a href="http://www.romeo.com">Romeo</a>',
];

$description = "Jack and Jill are friends. They want to go to France. They've met Romeo over there.";

$result = strtr($description, $trans);

Documentation: https://www.php.net/manual/en/function.strtr.php

sksighna's avatar

Thank you very much. But what if i need to set an url dynamically based on the name instead of direclty wiriting like in $trans Variable.

MichalOravec's avatar
$names = ['Jack', 'Jill', 'Romeo'];

$description = "Jack and Jill are friends. They want to go to France. They've met Romeo over there.";

$result = preg_replace('/('.implode('|', $names).')/', '<a href="http://www.$1.com">$1</a>', $description);

// or

$result = preg_replace_callback('/('.implode('|', $names).')/', function ($word) {
  return '<a href="http://www.'.strtolower($word[1]).'.com">'.$word[1].'</a>';
}, $description);

Please or to participate in this conversation.