php - 在字符串中查找字符并将它们作为 php 中的链接
问题描述
我在 Wordpress 中有 1000 多个帖子,其中包含用于正文中超链接的奇怪代码。例如,我想找到这个的所有实例:
[Website Name](http://www.website.com)
并将其变成
<a href="http://www.website.com">Website Name</a>
在 php 中实现这一目标的最佳方法是什么?
$string = "This is a blog post hey check out this website [Website Name](http://www.website.com). It is a real good domain.
// do some magic
解决方案
您可以使用preg_replace
此正则表达式:
\[([^]]+)]\((http[^)]+)\)
它查找 a [
,然后是一些非]
字符、a]
和(http
,然后是一些非)
字符,直到 a )
。
然后将其替换为<a href="$2">$1</a>
。例如:
$string = "This is a blog post hey check out this website [Website Name](http://www.website.com). It is a real good domain.";
echo preg_replace('/\[([^]]+)]\((http[^)]+)\)/', '<a href="$2">$1</a>', $string);
输出:
This is a blog post hey check out this website <a href="http://www.website.com">Website Name</a>. It is a real good domain.
推荐阅读
- java - 如何在 Java 中使用 Soap 记录错误请求
- sql - 原始 SQL_Flask SQLAlchemy:在绑定参数中使用列表
- sml - 如何正确读取这个使用 foldl 的 SML 函数?
- assembly - NASM - 宏本地标签作为另一个宏的参数
- mediawiki - 如何等待 Wikibase 编辑链接完成加载
- python - 如何在 matplotlib + PyQT5 中激活 WebGL 流?
- c# - 通过 x,y 识别所选按钮的最佳方法是什么
- datatables - DataTables 添加 aria 角色和 aria 扩展为详细信息控件(加号/减号按钮)
- apache-kafka - kafka流客户端能否以编程方式确定其消费者滞后
- r - knitr 在文档中生成错误,但无论如何都会正确生成数字