PHP:提取数字并用函数替换字符串中的所有匹配项

时间:2018-01-28 20:36:32

标签: php regex string preg-replace replaceall

我有这个字符串:

override func viewDidLoad() {
    super.viewDidLoad()
        ...

    bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
    bannerView.rootViewController = self
    bannerView.load(GADRequest())
}

我希望将所有 $string = '[userid=77] has created a new task. [userid=59] and [userid=66] is are subscribed. This task is assigned to [accountid=2248]'; 替换为[userid=DIGIT],将所有displayuser(DIGIT)替换为[accountid=DIGIT]

所以字符串应该像这样结束:

displayaccount(DIGIT)

到目前为止我尝试过的只显示第一个 $string = displayuser(77).' has created a new task. '.displayuser(59).' and '.displayuser(66).' is are subscribed. This task is assigned to '.displayaccount(2248).';

[userid=DIGIT]

2 个答案:

答案 0 :(得分:1)

您可以使用匹配并捕获useridaccountid以及preg_replace_callback function之后的数字的正则表达式,它将捕获的值映射到传递的匿名回调函数中的必要字符串作为第二个论点:

$text = preg_replace_callback('@\[userid=(\d+)]|\[accountid=(\d+)]@', function($m) {
    return !empty($m[1]) ? displayuser($m[1]) : displayaccount($m[2]);
}, $text);

请参阅PHP demo

\[userid=(\d+)]|\[accountid=(\d+)]模式将匹配[userid=<DIGITS_HERE>]将数字放入第1组或[accountid=<DIGITS_HERE>]将这些数字放入第2组。在回调中使用!empty($m[1])检查是否为Group 1匹配,如果是,请使用displayuser($m[1])按用户ID获取用户名,否则我们使用displayaccount($m[2])按帐户ID获取帐户名称。

答案 1 :(得分:1)

根据@ h2ooooooo的建议使用preg_replace_callback,我提出了以下完美的工作

$text = "[userid=77] has created a new task. [userid=59] and [userid=66] is are subscribed. This task is assigned to [accountid=4]";

function displaycontact_cb($matches){
  $found2 = preg_match('!\d+!', $matches[0], $match_id);
  return displayuser($match_id[0]);
}

function displayaccount_cb($matches){
  $found2 = preg_match('!\d+!', $matches[0], $match_id);
  return displaycontact($match_id[0],"account");
}

$text = preg_replace_callback('@\[userid[^\]]+\]@',"displaycontact_cb",$text);
$text = preg_replace_callback('@\[accountid[^\]]+\]@',"displayaccount_cb",$text);

print $text;