如何在@之后提取所有用户名和ID并建立链接
Hello @[user name1](id:1) i'm @[user name2](id:20)
是
hell [user name1][1] i'm [user name2][2]
[1]: http://dadasds.com/index.php?u=1
[2]: http://dasdasds.com/index.php?u=20
答案 0 :(得分:0)
找到这个:
@\[(.*?)\]\(id:(.*?)\)
替换为:
<a href="something" id ="\2">\1</a>
你会得到这样的结果:
Hello <a href="something" id ="1">user name1</a> i'm <a href="something" id ="20">user name2</a>
答案 1 :(得分:0)
使用此 Regular Expression Pattern
/\[([^)]+)\]\(id:(.*?)\)/.
<?php
$str="Hello @[user name1](id:1) i'm @[user name2](id:20)";
preg_match_all('/\[([^)]+)\]\(id:(.*?)\)/', $str, $matches);
print_r($matches[1]);
print_r($matches[2]);
?>
Array ( [0] => user name1 [1] => user name2 )
Array ( [0] => 1 [1] => 20 )
仅限用户名模式
/\[([^)]+)\]/
<?php
$str="Hello @[user name1](id:1) i'm @[user name2](id:20)";
preg_match_all('/\[([^)]+)\]/', $str, $matches);
print_r($matches[1]);
?>
Array ( [0] => user name1 [1] => user name2 )
答案 2 :(得分:0)
使用preg_replace_callback
的方式:
$data = <<<'EOD'
Hello @[user name1](id:1) i'm @[user name2](id:20)
EOD;
$pattern = '~@\[[^]]+]\K\(id:(\d+)\)~';
$linkList = array();
$path = 'http://the.path.com/index.php?u=';
$count = 0;
$result = preg_replace_callback($pattern,
function ($m) use (&$linkList, $path, &$count) {
$id = '[' . ++$count . ']';
$linkList[] = $id . ': ' . $path . $m[1];
return $id;
}, $data);
$result .= str_repeat(PHP_EOL, 4) . implode(PHP_EOL, $linkList);
echo $result;