php - 在文本中搜索单词并替换它们
问题描述
我很难找到解决问题的方法。
我在变量中有一个这样的数组:
$myarray = Array (
[0] => Orange
[1] => Black
[2] => White
[3] => Yellow
[4] => Red
);
基本上,我需要在字符串中搜索数组的单词,并将它们替换为相同的单词,但使用链接。
例如,来自:
$string = "My content contains orange and also blue";
至:
$string = "My content contains <a href="www.domain.com/orange">orange</a> and also blue";
解决方案
这可能最好使用preg_replace
. 我们可以通过使用implode
来创建一个正则表达式来创建每个单词的交替$myarray
; 在组中捕获该单词,然后在替换中使用它以在其周围添加链接:
$string = "My content contains orange and also blue in a blackout";
$string = preg_replace('/\b(' . implode('|', $myarray) . ')\b/i', '<a href="www.domain.com/$1">$1</a>', $string);
echo $string;
输出:
My content contains <a href="www.domain.com/orange">orange</a> and also blue in a blackout
请注意,通过使用带有单词边界 ( \b
) 的正则表达式,我们可以避免无意中将black
in替换blackout
为链接。
推荐阅读
- laravel - Laravel默认身份验证iis8.5不起作用
- docker - 在 docker 容器中出现错误“/usr/local/bin/docker-entrypoint.sh: 16: exec: redis-server --port 6000: not found”
- c# - 动态创建的 c# 标签不可见
- vb.net - 单击打印按钮时我的 DataGridView 出现故障
- html - 无法将菜单上的文本对齐到右侧
- python - Python:从一个子组中提取最小值,从另一个子组中提取最大值
- php - 如何修复由 JSON 内容中的负数引起的 php file_get_contents 警告?
- python - 试图将字节数组中的字节分成两个半字节
- c# - 水晶报表参数问题
- rest - testcafe是否支持测试rest api