简体   繁体   中英

append using preg_replace

I want to rename duplicate entries in PHP doc blocks:

 * @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:

$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:

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

To get the entire match, you can use "$0" in the replacement area.

Final code

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

$0 represents the entire part of the string that matches the pattern. $1 and so on represent the subpatterns.
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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