PHP str_replace 函数 [英] PHP str_replace with function

查看:37
本文介绍了PHP str_replace 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 str_replace() 并在替换中使用函数?

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

$value = "gal($data)";

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

gal($data) 是一个函数,我需要为这个函数替换一个代码并显示,但脚本最终只给了我这个 gal($data),并且函数没有显示

gal($data) is a function and I need replace one code for this function and show, but the script only give me finally this gal($data), and the function no show nothing

是否可以使用 str_replace() 来替换代码并用函数或类似的方法替换?

Is it possible use str_replace() for replace code and replace by the function or some similar method?

推荐答案

PHP 有一个名为 preg_replace_callback 就是这样做的.当您向它传递回调函数时,它将通过您的函数传递每个匹配项.您可以根据匹配的值选择替换或忽略它.

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.

举个例子,假设我有一个匹配各种字符串的模式,例如 [a-z]+.我可能不想用相同的值替换每个实例,所以我可以在找到eat match 时调用一个函数,并确定我应该如何响应:

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.

另一个例子是查找.假设我们想找到编程语言的缩写,并用它们的完整标题替换它们.我们可能有一个以缩写作为键,以长名称作为值的数组.然后我们可以使用我们的回调能力来查找全长名称:

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;

所以每次我们的正则表达式找到匹配项时,它都会通过lookup 传递匹配项,我们可以返回适当的值,或者原始值.

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.

这篇关于PHP str_replace 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆