Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php正则表达式获取用户名和id_Php_Regex - Fatal编程技术网

Php正则表达式获取用户名和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="

如何提取@之后的所有用户名和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="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;