PHP Tips: Use functions to replace keywords only a specified number of times

In PHP development, we often encounter situations where we need to replace a certain keyword in a string. Normally, we can use the built-in string replacement function str_replaceto accomplish this task. However, str_replacethe function replaces all matching keywords, and sometimes we only need to replace a few occurrences of them. This article will introduce a method to use a custom function to replace keywords only a specified number of times.

First, let's define a replace_keywordfunction called , which accepts four parameters: the string to be replaced $string, the keyword to be replaced $keyword, the replaced content $replacement, and the number of replacements $limit.

function replace_keyword($string, $keyword, $replacement, $limit) {
   
    
    
    

Guess you like

Origin blog.csdn.net/update7/article/details/133410824