【发布时间】:2018-01-28 20:36:31
【问题描述】:
我有这个字符串:
$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).';
到目前为止我尝试过的只显示 first [userid=DIGIT]。
$text = "[userid=77] has created a new task. [userid=59] and [userid=66] is are subscribed. This task is assigned to [accountid=28]";
print "Before: ".$text."<br/><br/>";
$matches = array();
// Get [userid=DIGIT]
$found = preg_match('@\[userid[^\]]+\]@', $text, $matches);
print $matches[0]."<br/><br/>";
// Get DIGIT withing [userid=DIGIT]
$found2 = preg_match('!\d+!', $matches[0], $match_id);
echo $match_id[0]."<br/><br/>";
// Replace [userid=DIGIT] with function(DIGIT)
$new = str_replace($matches[0],displayuser($match_id[0]),$text);
【问题讨论】:
-
看来您想使用
preg_replace_callback匹配正则表达式 ($pattern)~\[([a-z]+)=(\d+)\]~并用适当的函数调用替换文本。 -
请展示你的尝试。
-
@h2ooooooo 但是 preg_replace_callback 只会获得第一次出现或用户 ID 或其他。没有?
-
绝对不是。它会为每场比赛调用回调。如果它只匹配一个匹配,为什么它会有一个限制变量?
-
@h2ooooooo 请查看我的编辑,因为我尝试匹配(每个?) [userid=DIGIT],获取数字并将其替换为它的功能。似乎有效,但仅适用于第一次出现而不是每次出现。抱歉,我对 PHP 还很陌生。
标签: php regex string preg-replace replaceall