PHP 在“@”字符之后获取文本中的所有匹配字符串


php get all matches string in text after "@" character

我有这个函数,我希望设置文本从文本返回一些匹配字符串:

function get_matches(){
    $string = "@text1 @text2 any text here #text3 #text4 @text5 ";
    // Set the test string.
    // Set the regex.
    $regex = 'WHAT IS THE REGEX HERE';
    // Run the regex with preg_match_all.
    preg_match_all($regex, $string, $matches);
    // Dump the resulst for testing.
    echo '<pre>';
    print_r($matches);
    echo '</pre>';
}

结果 :

Array(
[0] => Array
    (
        [0] => text1
        [1] => text2
        [2] => text5
    ))

如何编写适当的正则表达式以获得正确的结果。

这个正则表达式应该适合你:

$regex = '/@('S+)/';

输出:

Array
(
    [0] => Array
        (
            [0] => @text1
            [1] => @text2
            [2] => @text4
            [3] => @text5
        )
    [1] => Array
        (
            [0] => text1
            [1] => text2
            [2] => text4
            [3] => text5
        )
)