简体   繁体   English

使用preg_replace追加

[英]append using preg_replace

I want to rename duplicate entries in PHP doc blocks: 我想重命名PHP doc块中的重复条目:

 * @property \App\Models\Invitation[] $invitations
 * @property \App\Models\Invitation[] $invitations

should become 应该成为

 * @property \App\Models\Invitation[] $invitations
 * @property \App\Models\Invitation[] $invitations2

I already have code that identifies duplicates and then I iterate over the property names that I want to append the number to: 我已经有了识别重复项的代码,然后遍历要在其后附加数字的属性名称:

preg_replace('/\@property [^ ]* \$' . $property . '/', ..., $docBlock)

I am just struggeling to find a way to use the text that if finds with the regex in the replacement statement: 我只是在努力寻找一种方法来使用如果在替换语句中使用正则表达式找到的文本:

preg_replace('/\@property [^ ]* \$' . $property . '/', MATCHED_TEXT.$i , $docBlock

preg_replace_callback solution: preg_replace_callback解决方案:

$docBlock = '
* @property \App\Models\Invitation[] $invitations
* @property \App\Models\Invitation[] $invitations
* @property \App\Models\Invitation[] $invitations';

$property = 'invitations';
$c = 0;  // count
$result = preg_replace_callback('/(\@property \S* \$)('. $property .')/', function ($m) use(&$c){
    return $m[1] . $m[2] . (++$c == 1? '' : $c);
}, $docBlock);

print_r($result);

The output: 输出:

* @property \App\Models\Invitation[] $invitations
* @property \App\Models\Invitation[] $invitations2
* @property \App\Models\Invitation[] $invitations3

I guess what you are trying to do is get everything caught by the regex ( MATCHED_TEXT ) in this piece of code: 我想您想做的是在这段代码中让正则表达式( MATCHED_TEXT )捕获所有内容:

preg_replace('/\@property [^ ]* \$' . $property . '/', MATCHED_TEXT.$i , $docBlock)

To get the entire match, you can use "$0" in the replacement area. 要获得全部匹配,您可以在替换区域中使用"$0"

Final code 最终代码

preg_replace('/\@property [^ ]* \$' . $property . '/', '$0'.$i , $docBlock)

$0 represents the entire part of the string that matches the pattern. $ 0表示与模式匹配的字符串的整个部分。 $1 and so on represent the subpatterns. $ 1等代表子模式。
Reference: Niet the Dark Absol 参考: 《黑暗的绝对伏击》

A simpler version without regex. 没有正则表达式的简单版本。
I use a temp array with the key name the same as string line and value is the "number". 我使用一个临时数组,其键名与字符串行相同,值是“数字”。
Then it's just a matter of looping and adding the number to the line. 然后,只需循环并将数字添加到该行即可。

$str = '@property \App\Models\Invitation[] $invitations
@property \App\Models\Invitation[] $invitations
@blogpost
@blogpost
@blogpost
@blogpost';

$arr = explode("\n", $str);

$temp = array();
Foreach($arr as &$item){
    If(isset($temp[$item])){
        $key = $item;
        $item .= $temp[$item];
        $temp[$key] = $temp[$key]+1;
    }Else{
        $temp[$item] = 2;
    }
}
Echo implode("\n",$arr);

https://3v4l.org/i1bCv https://3v4l.org/i1bCv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM