我正在研究类似于twitters的回复系统
在一个字符串中有一段文字,其中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中执行此操作?提前谢谢!
答案 0 :(得分:2)
如果您知道ID,那很简单:
<?php
$tweet_id = '14';
$replaced = str_replace("{$tweet_id}&", "<u>{$tweet_id.}&</u>", $original);
如果不这样做,请preg_replace
<?php
//look for 1+ decimals (0-9) ending with '$' and replaced it with
//original wrapped in <u>
$replaced = preg_replace('/(\d+&)/', '<u>$1</u>', $original);
答案 1 :(得分:2)
使用带有preg_replace功能的正则表达式。
<?php
$str = '14& this is a reply to the comment with id 14';
echo preg_replace('(\d+&)', '<u>$0</u>', $str);
正则表达式匹配:一个或多个数字后跟一个&符号。
答案 2 :(得分:2)
$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
将是您的身份证明。您可以用您喜欢的任何内容替换标记。
例如一个链接:
$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)