Php正则表达式获取用户名和id
如何提取@之后的所有用户名和id并创建链接Php正则表达式获取用户名和id,php,regex,Php,Regex,如何提取@之后的所有用户名和id并创建链接 Hello @[user name1](id:1) i'm @[user name2](id:20) 将来 找到这个: @\[(.*?)\]\(id:(.*?)\) 替换为: <a href="something" id ="\2">\1</a> 您将得到如下结果: Hello <a href="something" id ="1">user name1</a> i'm <a href="
Hello @[user name1](id:1) i'm @[user name2](id:20)
将来
找到这个:
@\[(.*?)\]\(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>
你好,我是
此处演示:使用此
/\[([^)]+)\]\(id:(.*?)\)/.
PHP
检查这个
仅获取用户名模式
/\[([^)]+)\]/
PHP
用
preg\u replace\u 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;
$data=
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 )
$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;