0

我的页面 php 中有这样的字符串:

$string = 'this is a test for @john and I can do all @mike';

我想把这个字符串找到它里面的所有字符串,@然后用它来查找具有该用户 ID 的用户的名称(如果存在)并转换成一个链接,变成这样的东西:

 $string = 'this is a test for <a href="/user?id=111">@john</a> and I can do all <a href="/user?id=112">@mike</a>';

如何获取所有字符串并使用它来查找该用户的 id,然后用链接替换原始字符串?

我知道使用preg_match我可以将字符串放入其中,但是如何使用该字符串?安藤如何构造这个表达式来取名字@

谢谢

4

4 回答 4

1

如果你有一个函数,比如 ,link()它接受字符串john并返回适当的链接:

preg_replace_callback('/@(\w+)/', function($matches) {
    return link($matches[1]);
}, $string);

或者,对于较旧的 PHP 版本:

preg_replace('/@(\w+)/e', 'link(\'$1\')', $string);
于 2013-07-29T10:45:45.220 回答
1

我会使用preg_match_all以下代码将从字符串中提取每个单词,@并将其返回到一个名为$matches. 然后,您可以循环遍历数组,对其进行比较并根据您的需要进行调节。

$string = 'this is a test for @john and I can do all @mike';

preg_match_all('/(?!\b)(@\w+\b)/', $string, $matches);
于 2013-07-29T10:52:04.287 回答
0

我会利用这个preg_match_all()功能。

之后,我将遍历匹配项并检索它们的 ID,并为每个匹配项生成适当的链接,将它们存储在一个数组中,让我们称之为它$links

此时我将有两个数组:

  1. $matches- 这将包含我的模式的所有出现
  2. $links- 它将包含 1-1 对应关系中的所有相应链接。

最后我会preg_replace()以以下方式使用:

preg_replace($matches, $links, $initial_string);

这会将在$matches中找到的每个项目替换$initial_string为来自 的相应项目$links

我希望我对你有所帮助。也许以后我也可以提供一些代码。

于 2013-07-29T10:55:24.863 回答
0
$string = 'this is a test for @john and I can do all @mike';
$result = preg_replace('/([^@]+)([^\s]+)/simx', '$1<a href="yourlink">$2</a>', $string);

echo $result;

输出

this is a test for <a href="yourlink">@john</a> and I can do all <a href="yourlink">@mike</a>
于 2013-07-29T10:44:31.553 回答