1

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! RT www.google.com : visited!

needs to be converted to:

<a href="http://twitter.com/username">username</a>: nice site! RT www.google.com : visited!

I've already got the following regex that converts the string @twitter to a clickable URL:

E.g.

$description = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $description);

Any ideas : )

CLiown
  • 13,665
  • 48
  • 124
  • 205

5 Answers5

3

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));
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
1
$regEx = "/^([^:\s]*)(.*?:)/";
$replacement = "<a href=\"http://www.twitter.com/\1\" target=\"_blank\">\1</a>\2";
Jacob Eggers
  • 9,062
  • 2
  • 25
  • 43
0

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);
Emre Yazici
  • 10,136
  • 6
  • 48
  • 55
0

The following should work -

$description = preg_replace("/^(.+?):\s@twitter\s(.+?)$/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>: \\2", $description);
Abhijit
  • 895
  • 5
  • 11
0

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+)/.

Karolis
  • 9,396
  • 29
  • 38