我正在使用php。我有一些动态的绳子。现在我想在字符串后面加一些数字。比如,我有一个字符串this is me (1)
。现在,我想在-7
之后添加1
。所以这个字符串应该像这个this is me (1-7)
那样打印。我已经通过使用substr_replace
正确地做到了这一点。像这样
substr_replace('this is me (1)','-59',-1,-1)
现在,如果有多个像这个this is me(2,3,1)
这样的数字。我想在每个数字之后添加-7
。就像这个this is me(2-7,3-7,1-7).
请帮帮忙。提亚
发布于 2018-07-16 12:36:38
我不知道是否有一个好的方法来做到这一点,在一两行,但我提出的解决方案如下:
$subject = "this is me (2,3,1)";
if (preg_match('[(?<text>.*)\((?<numbers>[0-9,]+)\)]', $subject, $matches)) {
$numbers = explode(",", $matches['numbers']);
$numbers = array_map(function($item) {
return $item.'-7';
}, $numbers);
echo $matches['text'].'('.implode(",", $numbers).')';
}
这里发生的情况如下:
preg_match
检查文本是否符合我们所需的格式。numbers
从捕获的名为explode
的组生成一个数组https://stackoverflow.com/questions/51361792
复制相似问题