PHP str_replace with function

后端 未结 1 425
清酒与你
清酒与你 2021-01-18 17:08

Is it possible use str_replace() and use function in replace?

$value = \"gal($data)\";

$replace = str_replace($dat, $value, $string);


        
相关标签:
1条回答
  • 2021-01-18 17:13

    PHP has a function called preg_replace_callback that does this. When you pass it a callback function, it will pass each match through your function. You can choose to replace, based upon the matched value, or ignore it.

    As an example, suppose I have a pattern that matches various strings, such as [a-z]+. I may not want to replace every instance with the same value, so I can call a function upon eat match found, and determine how I ought to respond:

    function callback ($match) {
        if ($match[0] === "Jonathan")
            return "Superman";
        return $match[0];
    }
    
    $subject = "This is about Jonathan.";
    $pattern = "/[a-z]+/i";
    $results = preg_replace_callback($pattern, "callback", $subject);
    
    // This is about Superman.
    echo $results;
    

    Note in our callback function how I am able to return special values for certain matches, and not all matches.

    Expanding Abbreviations

    Another example would be a lookup. Suppose we wanted to find abbreviations of programming languages, and replace them with their full titles. We may have an array that has abbreviations as keys, with long-names as values. We could then use our callback ability to lookup the full-length names:

    function lookup ($match) {
        $langs = Array(
            "JS"  => "JavaScript", 
            "CSS" => "Cascading Style Sheets", 
            "JSP" => "Java Server Pages"
        );
        return $langs[$match[0]] ?: $match[0];
    }
    
    $subject = "Does anybody know JS? Or CSS maybe? What about PHP?";
    $pattern = "/(js|css|jsp)/i";
    $results = preg_replace_callback($pattern, "lookup", $subject);
    
    // Does anybody know JavaScript? Or Cascading Style Sheets maybe? What about PHP?
    echo $results;
    

    So every time our regular expression finds a match, it passes the match through lookup, and we can return the appropriate value, or the original value.

    0 讨论(0)
提交回复
热议问题