2012-03-25 70 views
1

我正在研究类似于推特的回复系统。
在一个字符串中有一段文字,其中id是可变的,例如:14&138&,具体取决于您要回复的人。
如何在字符串中找到14&并将其替换为<u>14&</u>用PHP中的变量文本替换精确的变量字符串?

这是它的外观:

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

空间,任何规模的数量和空间,然后 - 是正确的? – 2012-03-25 21:45:29

+0

@Dagon是的,这是正确的。 :) – 2012-03-25 21:46:03

+0

你是否希望它也取代3和4在下面,或者应该被排除? '1&开头。 2&在中间。 3和后面跟着一个词。 And4&前面有一个词。最后以5'结尾? – 2012-03-25 22:05:10

回答

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会你的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) 
+0

这样做的窍门,谢谢你! – 2012-03-25 21:58:54

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); 
+0

如果我不知道ID? – 2012-03-25 21:47:12

+0

我扩展了我的答案:它使用[preg_replace](http://php.net/manual/en/function.preg-replace.php) – 2012-03-25 21:52:04

2

使用正则表达式的preg_replace功能。

<?php 

$str = '14& this is a reply to the comment with id 14'; 
echo preg_replace('(\d+&)', '<u>$0</u>', $str); 

正则表达式匹配:一个或多个数字后跟一个&号。