将字符串中的所有奇数单词编辑为大写



我需要将所有奇数单词编辑为大写。

下面是输入字符串的示例:

very long string with many words

预期产出:

VERY long STRING with MANY words

我有这段代码,但它对我来说,我可以以更好的方式做到这一点。

<?php
$lines = file($_FILES["fname"]["tmp_name"]);
$pattern = "/(S[w]*)/";
foreach($lines as $value)
{
    $words = NULL;
    $fin_str = NULL;
    preg_match_all($pattern, $value, $matches);

    for($i = 0; $i < count($matches[0]); $i = $i + 2){
        $matches[0][$i] = strtoupper($matches[0][$i]);
        $fin_str = implode(" ", $matches[0]);
    }
    echo $fin_str ."<br>";

附言我只需要使用preg_match功能。

下面是

一个preg_replace_callback的例子:

<?php
$str = 'very long string with many words';
$newStr = preg_replace_callback('/([^ ]+) +([^ ]+)/', 
     function($matches) {
         return strtoupper($matches[1]) . ' ' . $matches[2];
      }, $str);
print $newStr;
// VERY long STRING with MANY words
?>

您只需要匹配重复模式:/([^ ]+) +([^ ]+)/,一对单词,然后preg_replace_callback递归字符串,直到匹配和替换所有可能的匹配项。 preg_replace_callback调用 strtoupper 函数并将捕获的反向引用传递给它所必需的。

演示

如果你必须使用正则表达式,这应该可以帮助你开始:

$input = 'very long string with many words';
if (preg_match_all('/s*(S+)s*(S+)/', $input, $matches)) {
    $words = array();
    foreach ($matches[1] as $key => $odd) {
        $even = isset($matches[2][$key]) ? $matches[2][$key] : null;
        $words[] = strtoupper($odd);
        if ($even) {
            $words[] = $even;
        }
    }
    echo implode(' ', $words);
}

这将输出:

VERY long STRING with MANY words

您可能不需要正则表达式,只需使用 explode 并再次连接字符串:

<?php
function upperizeEvenWords($str){
   $out = "";
   $arr = explode(' ', $str);
   for ($i = 0; $i < count($arr); $i++){
      if (!($i%2)){
         $out .= strtoupper($arr[$i])." ";
      }
      else{
          $out .= $arr[$i]." ";
      }     
   }
   return trim($out);
}
$str = "very long string with many words";
echo upperizeEvenWords($str);

查看此演示

最新更新