0

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

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


例如
arraypart1 (应该保持大写) (constantword)+arraypart2 (都应该变成小写字母)

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

4

2 回答 2

0

不是 100% 清楚你想要做什么,但我认为它是以下内容:从字符串中提取单词,并根据它们在数组之一中的存在情况提取其中一些单词。preg_replace_callback会帮助你。

PHP 5.3 及更高版本:

$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:

$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关键字引用它们。

于 2012-07-22T17:22:57.483 回答
-1

我希望我理解正确,preg_replace是一个函数,就像你可以做的所有其他函数一样:

preg_replace(strtolower($val),$pattern,$someString);

preg_replace将使用小写版本的$val

于 2012-07-22T10:26:49.697 回答