我正在尝试执行多个搜索,并在给定前缀列表的字符串中替换。
例如:$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);
}
你的新line变量将有三个url附加到它上面,如所示,但是你可以对它做任何你想做的修改。