<?php
/**
* This is the body field of my database article table. $body
* "<p style="margin:20px auto; font-size:20px;">每天都有好心情,我真的很开心 Very happy! oh yes</p>"
*
* */
$body = '<p style="margin:20px auto; font-size:20px;">每天都有好心情,我真的很开心 Very happy! oh yes</p>';
$str = htmlspecialchars_decode($body);
$keywords = [
0=>['id'=>1,'slug'=>'好心情','url'=>'https://www.example.com/goodMood'],
1=>['id'=>2,'slug'=>'开心','url'=>'https://www.example.com/happy'],
2=>['id'=>3,'slug'=>'happy','url'=>'https://www.example.com/happy1'],
];
//I want to convert to this format:
$result = '<p style="margin:20px auto; font-size:20px;">每天都有<a href="https://www.example.com/goodMood">好心情</a>,我真的很<a href="https://www.example.com/happy">开心</a> Very <a href="https://www.example.com/happy1">happy</a>! oh yes</p>';
$reps = array_combine(array_column($keywords, 'slug'),
array_map(function ($k) { return '<a href="' . $k['url'] .'">' . $k['slug'] . '</a>'; }, $keywords
));
$newstr = strtr($str, $reps);
echo "$newstr\n$result";
preferences:
23.55 ms | 408 KiB | 5 Q