php - 用 PHP 中的变量文本替换确切的变量字符串?

标签 php mysql string function

我正在开发一个类似于推特的回复系统。
在一个字符串中有一段文本,其中 id 是可变的,例如:14& , 138&取决于你回复的人。
我怎样才能找到 14&在一个字符串中并将其替换为 <u>14&</u>

它是这样的:

14& this is a reply to the comment with id 14

它应该是这样的:

<u>14&</u> this is a reply to the comment with id 14

我如何在 PHP 中执行此操作?提前致谢!

最佳答案

$text = "14& this is a reply to the comment with id 14";

var_dump(preg_replace("~\d+&~", '<u>$0</u>', $text));

输出:

string '<u>14&</u> this is a reply to the comment with id 14' (length=52)

去除&:

preg_replace("~(\d+)&~", '<u>$1</u>', $text)

输出:

string '<u>14</u> this is a reply to the comment with id 14' (length=51)

$0$1 将是您的 ID。您可以将标记替换为您喜欢的任何内容。

例如链接:

$text = "14& is a reply to the comment with id 14";

var_dump(preg_replace("~(\d+)&~", '<a href="#comment$1">this</a>', $text));

输出:

string '<a href="#comment14">this</a> is a reply to the comment with id 14' (length=66)

关于php - 用 PHP 中的变量文本替换确切的变量字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9864349/

相关文章:

php - 检查数据库的相似值,MySQL

javascript - 如何在 MySQL 数据库中保存 jquery keyup() 的每个输入值?

php - 下拉菜单和 MySQl

php - 如何在php代码中嵌入html文件?

两个日期戳之间的MySQL时间选择

string - Lua gmatch 奇数字符(斯洛伐克字母)

PHP 和 MySQL。想要显示目录的第一张图像。数据库的目录路径

php - 无法使用 PHP 和 MySQL 让数据库更新上次登录时间?

C - 如果 else scanf 未按预期工作

java - 在Java中将十六进制字符串转换为ASCII