PHP str_replace()是否具有限制参数? [英] PHP str_replace() with a limit param?

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

问题描述

str_replace用替换词替换所有出现的单词.

str_replace replaces all occurrences of a word with a replacement.

preg_replace用替换替换出现的模式,并采用可选的极限参数.

preg_replace replaces occurrences of a pattern with a replacement and takes an optional limit param.

我不需要任何模式匹配,但希望使用限制参数的便利.我应该使用什么?

I don't have any need for pattern matching but would like the convenience of a limit param. What should I be using?

推荐答案

function str_replace2($find, $replacement, $subject, $limit = 0){
  if ($limit == 0)
    return str_replace($find, $replacement, $subject);
  $ptn = '/' . preg_quote($find,'/') . '/';
  return preg_replace($ptn, $replacement, $subject, $limit);
}

这将使您可以限制替换次数.应该使用preg_quote对字符串进行转义,以确保不会将任何特殊字符解释为模式字符.

That will allow you to place a limit on the number of replaces. Strings should be escaped using preg_quote to make sure any special characters aren't interpreted as a pattern character.

Demo,BTW

如果您有兴趣,请此处是包含&$count参数的版本:

In case you're interested, here's a version that includes the &$count argument:

function str_replace2($find, $replacement, $subject, $limit = 0, &$count = 0){
  if ($limit == 0)
    return str_replace($find, $replacement, $subject, $count);
  $ptn = '/' . preg_quote($find,'/') . '/';
  return preg_replace($ptn, $replacement, $subject, $limit, $count);
}

这篇关于PHP str_replace()是否具有限制参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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