用链接替换文本中的名称
我想用指向该个人资料的链接替换文本中的姓名。
$text = "text with names in it (John) and Jacob.";
$namesArray("John", "John Plummer", "Jacob", etc...);
$LinksArray("<a href='/john_plom'>%s</a>", "<a href='/john_plom'>%s</a>", "<a href='/jacob_d'>%s</a>", etc..);
//%s shout stay the the same as the input of the $text.
但如有必要,可以更改数组。
我现在使用 2 个数组来使用 str_replace。像这样 $text = str_replace($namesArray, $linksArray, $text);
但用“点”或“)”或任何类似的东西在结尾或开头替换名称。我怎样才能让替换对这样的文本起作用。
输出喊叫是“其中包含名称的文本(
I want to replace names in a text with a link to there profile.
$text = "text with names in it (John) and Jacob.";
$namesArray("John", "John Plummer", "Jacob", etc...);
$LinksArray("<a href='/john_plom'>%s</a>", "<a href='/john_plom'>%s</a>", "<a href='/jacob_d'>%s</a>", etc..);
//%s shout stay the the same as the input of the $text.
But if necessary a can change de array.
I now use 2 arrays in use str_replace. like this $text = str_replace($namesArray, $linksArray, $text);
but the replace shout work for name with a "dot" or ")" or any thing like that on the end or beginning. How can i get the replace to work on text like this.
The output shout be "text with names in it (<a.....>John</a>) and <a ....>Jacob</a>."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是单个名称的示例,您需要对数组中的每个元素重复此操作:
Here is an example for a single name, you would need to repeat this for every element in your array:
尝试类似
PHP 的 preg_replace 接受混合模式和主题,换句话说,您可以提供像这样的模式数组和替换数组。
Try something like
PHP's preg_replace accepts mixed pattern and subject, in other words, you can provide an array of patterns like this and an array of replacements.
完成,并且没有正则表达式:
对于每个给定的输入,链接永远不会改变,所以我不确定我是否理解你的问题。但我已经测试过它并且它适用于给定的字符串。要扩展它,只需向
$name_link
数组添加更多条目即可。Done, and no regex:
The links will never change for each given input, so I'm not sure whether I understood your question. But I have tested this and it works for the given string. To extend it just add more entries to the
$name_link
array.寻找正则表达式。类似 preg_replace() 的东西。
请注意,此解决方案采用名称数组,而不仅仅是一个名称。
Look for regular expressions. Something like preg_replace().
Note that this solution takes the array of names, not just one name.