php - 在特定句子之间插入标签,保持原始大小写
问题描述
我需要在字符串中的某个文本之间插入一个 span 标签,但它应该不区分大小写并保留原始大小写。
$string ="This is what this is";
echo str_replace("this is","[span]this is[/span]",$string);
回报:
这就是 [span]这是[/span]
预期的:
[/span]这是[/span] 这是什么 [span]这是[/span]
我知道这str_replace
不是一个好的选择,而且 ir 可能由 Regex 处理,但我不知道我应该朝哪个方向发展。在此先感谢您的帮助!
解决方案
使用preg_replace:
$string ="This is what this is";
echo preg_replace("/this is/i","[span]$0[/span]",$string);
解释:
/ : regex delimiter
this is : literally
/i : regex delimiter, case insensitive
替代品:
$0 : contains the whole match, ie "this is"
推荐阅读
- mysql - 在数据库中保存原始 http 请求
- javascript - 如何使左侧 div 滚动位置跟随窗口滚动位置?
- python - 简单 if/else 语句的问题(不等于或条件) - Python
- java - 由于 SocketException 导致 DTLS 握手失败,尽管套接字从未通过菜单关闭
- bash - 管道 grep 的变量值未传递到远程 ssh
- amazon-web-services - 无法使用 VPC 端点登录 ECR
- bash - 我可以同时将 cmder 用于 Git Bash 和其他命令行功能,如 dotnet、ng 等吗?
- javascript - contenteditable="false" 属性不适用于角度 10 中动态创建的跨度
- ms-word - 在重新缩放科学数字和图表时保持相同的字体大小
- image - 为什么我的图像(本地资产或下载的资产)没有在 iOS 14 上显示,而是在使用 ReactNative 0.62.x 的 Android 上显示?