PHP 用 href 链接替换字符串中的关键字

发布于 2024-12-04 10:39:45 字数 281 浏览 1 评论 0原文

我今天早上很“厚”,所以请原谅这个简单的问题 - 我有一个关键字数组,例如 array('keyword1','keyword2'....) 并且我有一个文本字符串- (有点像博客内容的长度,即不仅仅是几个单词,而是可能有 200-800 个单词)搜索字符串中的关键字并将其替换为 href 链接的最佳方法是什么。因此,在文本中,“关键字 1”(作为纯文本)将变为 keyword1 等等。

看到说今天上午很厚。

提前致谢。

I am being "thick this morning" so please excuse this simple question - I have an array of keywords e.g. array('keyword1','keyword2'....) and I have a string of text - (bit like a blog content in length i.e. not just a few words but may be 200-800 words) what is the best way to search the string for the keywords and replace them with an href link. So in the text 'keyword 1' (as plain text) will become <a href='apage'>keyword1</a> and so on.

See said was being thick this am.

Thanks in adavance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晨曦慕雪 2024-12-11 10:39:45

典型的 preg_replace 案例:

$text = "There is some text keyword1 and lorem ipsum keyword2.";
$keywords = array('keyword1', 'keyword2');

$regex = '/('.implode('|', $keywords).')/i';

// You might want to make the replacement string more dependent on the
// keyword matched, but you 'll have to tell us more about it
$output = preg_replace($regex, '<a href="apage">\\1</a>', $text);

print_r($output);

< a href="http://www.ideone.com/Xu1Jf" rel="nofollow">查看实际操作

现在,上面的内容并没有进行非常“智能”的替换,因为 href 不是匹配关键字的函数,而实际上您可能会想要这样做。查看 preg_replace_callback此处更具灵活性,或编辑问题并提供有关您的目标的更多信息。

Typical preg_replace case:

$text = "There is some text keyword1 and lorem ipsum keyword2.";
$keywords = array('keyword1', 'keyword2');

$regex = '/('.implode('|', $keywords).')/i';

// You might want to make the replacement string more dependent on the
// keyword matched, but you 'll have to tell us more about it
$output = preg_replace($regex, '<a href="apage">\\1</a>', $text);

print_r($output);

See it in action.

Now the above doesn't do a very "smart" replace in the sense that the href is not a function of the matched keyword, while in practice you will probably want to do that. Look into preg_replace_callback for more flexibility here, or edit the question and provide more information regarding your goal.

Smile简单爱 2024-12-11 10:39:45

为什么要使用正则表达式而不是 str_replace() !?正则表达式有效,但它使如此简单的问题变得复杂化。

WHY would you use regex instead of just str_replace() !? Regex works, but it over complicates such an incredibly simple question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文