Php正则表达式获取用户名和ID

时间:2014-04-08 12:22:13

标签: php regex

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

3 个答案:

答案 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>

演示:http://regex101.com/r/hI3xQ7

答案 1 :(得分:0)

使用此 Regular Expression Pattern

/\[([^)]+)\]\(id:(.*?)\)/.

PHP

<?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 )

检查此 Demo CodeViper


仅限用户名模式

/\[([^)]+)\]/

PHP

<?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 )

检查此 Demo CodeViper

答案 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;