如何在文本中搜索字符串,并在php中替换链接


How to search for strings in text and replace with links in php

我目前正在将twitter feed拉入我的网站并在首页上显示内容。所有我希望能够做的是替换任何内容,是标签或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 }
?>
$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.

使用这些括号,您正在定义捕获组。当您在模式中使用捕获组时,您可以使用''n$n来引用它们,顺序从0到99。

所以你的替换将是:

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

如果你有更多的捕获组,你会有更多的数字。

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