# 如果當前文件中不存在特定字符串，如何添加？

I want to add this string "declare(strict_types=1);" after <?php when I save or open a file.

<?php
declare(strict_types=1);


## 最佳答案

function! AddPHPStrictTypes()
" Save the cursor position
let cursor_save = getpos('.')

" Go to the begining of the file
call cursor(1, 1)

" Get the line containing "<?php"
let phpLine = search('<?php')

" If the declaration isn't in the buffer and there is one line containing "<?php"
if search('<?php\ndeclare(strict_types=1);') == 0 && phpLine != 0
" Add the declaration after the line
call append(phpLine, "declare(strict_types=1);")
endif

" Restore cursor position
call setpos('.', cursor_save)
endfunction


We declare a function which searches for the declaration. If the declaration is not found it search for the line containing <?php and add the declaration after it.