2013-04-28 154 views
2

我试图执行多个搜索和替换字符串给定的前缀列表。preg_match多个搜索替换字符串

例如:

$string = "CHG000000135733, CHG000000135822, CHG000000135823"; 
if (preg_match('/((CHG|INC|HD|TSK)0+)(\d+)/', $string, $id)) { 
# $id[0] - CHG.* 
# $id[1] - CHG(0+) 
# $id[2] - CHG 
# $id[3] - \d+ # excludes zeros 

$newline = preg_replace("/($id[3])/","<a href=\"http://www.url.com/newline.php?id=".$id[0]."\">\\1</a>", $string); 
} 

这仅改变CHG000000135733。我怎样才能使代码工作,以取代其他两个CHG号码作为其相应号码的链接。

使用Casimir et Hippolyte提交的这段代码求解。

$newline = preg_replace ('~(?:CHG|INC|HD|TSK)0++(\d++)~', '<a href="http://www.url.com/newline.php?id=$0">$0</a>', $string); 
+0

'$ input'中有什么?你永远不会定义它。 – 2013-04-29 00:01:00

回答

1

之前不需要使用preg_match。在一行中:

$newline = preg_replace ('~(?:CHG|INC|HD|TSK)0++(\d++)~', '<a href="http://www.url.com/newline.php?id=$0">$1</a>', $string); 
+0

正是我在找的!谢谢! – user2001487 2013-04-29 16:42:03

0

你需要在它们之间迭代:

$string = "CHG000000135733, CHG000000135822, CHG000000135823"; 
$stringArr = explode(" ", $string); 
$newLine = ""; 
foreach($stringArr as $str) 
{ 
    if (preg_match('/((CHG|INC|HD|TSK)0+)(\d+)/', $str, $id)) { 
    # $id[0] - CHG.* 
    # $id[1] - CHG(0+) 
    # $id[2] - CHG 
    # $id[3] - \d+ # excludes zeros 

    $newline .= preg_replace("/($id[3])/","<a href=\"http://www.url.com/newline.php?id=".$id[0]."\">\\1</a>", $str); 
} 

新行变量将追加到它所有这三个网址如图所示,但你可以修改它做watever你想要的网址..