[英]preg_match multiple search replace in string
我正在嘗試執行多個搜索並替換給定前綴列表的字符串。
例如:
$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);
之前無需使用preg_match。 一行:
$newline = preg_replace ('~(?:CHG|INC|HD|TSK)0++(\d++)~', '<a href="http://www.url.com/newline.php?id=$0">$1</a>', $string);
您將需要遍歷它們:
$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);
}
如圖所示,新行變量將在其后附加所有三個網址,但您可以通過網址隨意修改它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.