-1

我目前正在将 twitter 提要放入我的网站并在首页上显示内容。我想要做的就是用链接替换标签或 Twitter 用户名的任何内容。

我尝试使用 preg_replace 执行此操作,但在构建用作替换的链接时遇到问题,因为我不确定如何引用和插入匹配的模式。这是我到目前为止的内容(未完成)。有谁能够帮助我?

谢谢!

<?php 
foreach($tweets as $tweet) { ?>
  <?php 
    $pattern = '@([A-Za-z0-9_]+)';
    $replacement = "<a href=''>" . . "</a>";
    $regex_text = preg_replace($pattern, );

  ?>
  <div class="tweet2">
    <img src="images/quotes.png" />
    <p><?php echo $tweet[text]; ?></p>
  </div>
<?php }
?>
4

2 回答 2

3
$regex_text = preg_replace($pattern, $replacement, $input_text);

这是使用 preg_replace 的正确方法,$input_text是带有要替换内容的文本的变量。

除此之外:

$pattern="/@([A-Za-z0-9_]+)/"; //can't be sure if this will work w/o an example of a input string.
$replacement= "<a href=''>$1</a>";  //$1 is what you capture between `()` in the pattern.
于 2013-03-21T16:23:34.863 回答
1

使用这些括号,您正在定义一个捕获组。当您在模式中使用捕获组时,您可以按顺序引用使用\\n或的那些$n,从 0 到 99。

所以你的替代品是:

$replacement = "<a href='http://twitter.com/$1'>$1</a>";

如果您有更多的捕获组,您将拥有更多的数字。

查看手册条目$replacement参数以获取更多信息。

于 2013-03-21T16:24:57.067 回答