PHP Regex to convert text before colon to link

前端 未结 5 864
逝去的感伤
逝去的感伤 2021-01-25 04:40

I need to find the first occurance of a colon \':\' and take the complete string before that and append it to a link.

e.g.

username: @twitter nice site!          


        
相关标签:
5条回答
  • 2021-01-25 05:24

    Direct answer to your question:

    $string = preg_replace('/^(.*?):/', '<a href="http://twitter.com/$1">$1</a>:', $string);
    

    But I assume that you are parsing twitter RSS or something similar. So you can just use /^(\w+)/.

    0 讨论(0)
  • 2021-01-25 05:30

    I'd use string manipulation for this, rather than regex, using strstr, substr and strlen:

    $username = strstr($description, ':', true);
    $description = '<a href="http://twitter.com/' . $username . '">' . $username . '</a>'
                 . substr($description, strlen($username));
    
    0 讨论(0)
  • 2021-01-25 05:35
    $regEx = "/^([^:\s]*)(.*?:)/";
    $replacement = "<a href=\"http://www.twitter.com/\1\" target=\"_blank\">\1</a>\2";
    
    0 讨论(0)
  • 2021-01-25 05:35

    The following should work -

    $description = preg_replace("/^(.+?):\s@twitter\s(.+?)$/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>: \\2", $description);
    
    0 讨论(0)
  • 2021-01-25 05:41

    I have not tested the code, but it should work as is. Basically you need to capture after @twitter too.

    $description = preg_replace("%([^:]+): @twitter (.+)%i", 
        "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>: \\2", 
        $description);
    
    0 讨论(0)
提交回复
热议问题