首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在preg_replace中执行PHP命令

在preg_replace中执行PHP命令
EN

Stack Overflow用户
提问于 2012-07-22 18:15:25
回答 2查看 332关注 0票数 0

是否可以通过preg_replace()执行php命令,例如strtolower()

我只想让一组数组的一部分变成小写字母,另一部分变成大写字母。问题是字母是动态变化的,不是固定的,只有一个单词保持不变,其余的则不变。

例如:

arraypart1 (应保持大写)(常量单词)+arraypart2(两者均应改为小写字母)

arraypart2也在改变字符数字的大小。

EN

回答 2

Stack Overflow用户

发布于 2012-07-23 01:22:57

不是100%清楚你想要做什么,但我认为它是这样的:从字符串中提取单词,并根据它们在一个数组中的存在来区分其中的一些小写/大写。preg_replace_callback会帮你的。

PHP 5.3及更高版本:

代码语言:javascript
运行
复制
$initial = "Mary had a little lamb";
$toupper = array("Mary", "lamb");
$tolower = array("had", "any");
$out = preg_replace_callback(
   "/\b(?P<word>\w+)\b/", // for every found word 
   function($matches) use ($toupper, $tolower) { // call this function 
      if (in_array($toupper, $matches['word'])) // is this word in toupper array?
          return strtoupper($matches['word']);

      if (in_array($tolower, $matches['word'])) // is this word in tolower array?
          return strtolower($matches['word']);

      // ... any other logic
      return $matches['word']; // if nothing was returned before, return original word
   },
   $initial);
print $out; // "MARY had a little LAMB"

如果您有其他需要考虑的数组,请将它们放在use语句中,以便在匿名函数中可用。

PHP >= 4.0.5:

代码语言:javascript
运行
复制
$initial = "Mary had a little lamb";
$toupper = array("Mary", "lamb");
$tolower = array("had", "any");

function replace_callback($matches) {  
   global $tolower, $toupper;
      if (in_array($toupper, $matches['word'])) // is this word in toupper array?
          return strtoupper($matches['word']);

      if (in_array($tolower, $matches['word'])) // is this word in tolower array?
          return strtolower($matches['word']);

      // ... any other logic
      return $matches['word']; // if nothing was returned before, return original word
   }

$out = preg_replace_callback(
   "/\b(?P<word>\w+)\b/", // for every found word 
   'replace_callback', // call this function
   $initial);
print $out; // "MARY had a little LAMB"

正如你所看到的,没有什么明显的变化,我只是用一个命名函数替换了匿名函数。要为它提供其他字符串数组,请使用global关键字引用它们。

票数 0
EN

Stack Overflow用户

发布于 2012-07-22 18:26:50

我希望我没弄错,preg_replace是一个函数,就像你可以做的所有其他函数一样:

代码语言:javascript
运行
复制
preg_replace(strtolower($val),$pattern,$someString);

将使用$val的小写版本调用preg_replace

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11599410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档