String replace with callback

suggest change

preg_replace_callback sends each match to the callback as the $matches array ($matches[0] is the whole match) and replaces that match with the callback's return value. This allows us to replace strings based on any kind of logic.

$subject = "He said 123abc, I said 456efg, then she said 789hij";
$regex = "/\b(\d+)\w+/";

// This function replaces the matched entries conditionally 
// depending upon the first character of the capturing group
function regex_replace($matches){
    switch($matches[1][0]){
        case '7':
            $replacement = "<b>{$matches[0]}</b>";
            break;
        default:
            $replacement = "<i>{$matches[0]}</i>";
    }
    return $replacement;
}

$replaced_str = preg_replace_callback($regex, "regex_replace", $subject);

print_r($replaced_str);
# He said <i>123abc</i>, I said <i>456efg</i>, then she said <b>789hij</b>

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents