PHP拆分字符串并将部分转换为链接

时间:2015-04-09 13:01:09

标签: php regex laravel

我的数据库中有这些可能的字符串:

"#111111 opened";
"#111111 opened";
"Opened ticket #111111";
"Opened ticket #111111 something else.";
"Opened ticket #111111 and ticket #222222";
"Opened ticket #111111 and ticket #222222 something else.";

我正在尝试更改该字符串以包含这样的链接:

Opened ticket <a href="http://siteOfTickets.com/ticket/111111" target="_blank">#111111</a> and ticket <a href="http://siteOfTickets.com/ticket/222222" target="_blank">#222222</a> something else.

我通过这样做来分割字符串:

$arrary1 = preg_split("/#[0-9]{6}/", $report->obs);
preg_match_all('/#[0-9]{6}/', $report->obs, $array2);

现在我很难完成这个。有一个简单的方法吗?

1 个答案:

答案 0 :(得分:1)

您最好使用preg_replace:

$str = preg_replace('/#(\d{6})\b/', 
       '<a href="http://siteOfTickets.com/ticket/$1" target="_blank">#$1</a> ',
        $report->obs);