我正在开发一个类似于推特的回复系统。
在一个字符串中有一段文本,其中 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/