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_replace
to accomplish this task. However, str_replace
the 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_keyword
function 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) {