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!
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+)/
.
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));
$regEx = "/^([^:\s]*)(.*?:)/";
$replacement = "<a href=\"http://www.twitter.com/\1\" target=\"_blank\">\1</a>\2";
The following should work -
$description = preg_replace("/^(.+?):\s@twitter\s(.+?)$/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>: \\2", $description);
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);