在下面的代码中假设#bob和#test匹配, preg_replace表达式是什么,以便#bob和#to是网址(即http://test.com/read.php?id=bob) ?请注意,id = bob部分没有#标签。
$text = "my name is #bob and I like #to #test things.";
preg_match_all("/(#\w+)/", $text, $matches);
foreach($matches['0'] as $match){
$substring = substr($match, 1);
$titlerows = mysql_num_rows(mysql_query("SELECT title FROM title WHERE title='$substring'"));
if($titlerows == 1) {
$text = preg_replace('/$match/', replace?? , $text);
}
}
echo $text;
答案 0 :(得分:1)
如果我理解你的问题,我希望这会对你有所帮助。
$text = preg_replace('/'.$match.'/', 'http://test.com/read.php?id='.substr($match,1) , $text);
编辑:
$text = preg_replace("/$match/", '<a href="http://test.com/read.php?id='.$substring.'">'.$match.'</a>' , $text);
答案 1 :(得分:1)
就像FeRtoll的答案一样,但这利用了我们之前已经substr()
做过的事实:
$text = preg_replace("/$match/", "http://test.com/read.php?id=.$substring", $text);
对于评论中更复杂的替换,请执行:
$text = preg_replace("/$match/", "<a href='http://test.com/read.php?id=$substring'>$match</a>", $text);
我喜欢插值而不是连接。