2013-04-28 155 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你想要的網址..