【问题标题】:preg_match multiple search replace in stringpreg_match 字符串中的多个搜索替换
【发布时间】:2013-04-22 13:43:10
【问题描述】:

我正在尝试在给定前缀列表的字符串中执行多重搜索和替换。

例如:

$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);

【问题讨论】:

  • $input 中有什么内容?你永远不会定义它。

标签: php regex search replace


【解决方案1】:

你需要遍历它们:

$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);
}

您的新行变量将添加所有三个 url,如图所示,但您可以随时使用 url 修改它。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 正是我想要的!谢谢!
    猜你喜欢
    • 2018-01-02
    • 2020-05-15
    • 2020-01-06
    • 2011-08-10
    • 1970-01-01
    • 2017-01-10
    • 2010-11-14
    • 1970-01-01
    相关资源
    最近更新 更多