【问题标题】:replace only the first instance of a substring仅替换子字符串的第一个实例
【发布时间】:2018-12-25 09:41:04
【问题描述】:
$patha = 'BIN/BIN/test.php';
$count = 1;
$pathb = str_replace('BIN', 'SYSTEM', $patha, $count);
echo $pathb;

结果:

SYSTEM/SYSTEM/test.php

我只想替换BIN 的第一个实例,所以结果应该是:

SYSTEM/BIN/test.php

如何做到这一点?

【问题讨论】:

标签: php


【解决方案1】:

您应该使用 preg_replace 和 $limit 参数

preg_replace('/BIN/', 'SYSTEM', $patha, 1);

因为 str_replace $count 参数在您等待时不受限制

【讨论】:

    【解决方案2】:

    来自手册:PHP: str_replace - Manual,这里清楚地说明了语法:

    mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

    然后是$count:

    count
    如果通过,这将设置为执行的替换次数。

    这不是替换的数量,功能要占用。您的 $count 值会更新,告知您已进行 2 次替换。要限制更换的数量,请使用preg_replace。或者手册中给出的其他功能:

    <?php
        /**
         * Replace $limit occurences of the search string with the replacement
         * @param mixed $search The value being searched for. An array may be used to
         * designate multiple needles.
         * @param mixed $replace The replacement value that replaces found search
         * values. An array may be used to designate multiple replacements.
         * @param mixed $subject The string or array being searched and replaced on. If
         * subject is an array, then the search and replace is performed with every
         * entry of subject, and the return value is an array as well. 
         * @param string $count If passed, this will be set to the number of
         * replacements performed.
         * @param int $limit The maximum possible replacements for each pattern in each
         * subject string. Defaults to -1 (no limit).
         * @return string This function returns a string with the replaced values.
         */
        function str_replace_limit($search, $replace, $subject, &$count, $limit = -1)
        {
            $count = 0;
            // Invalid $limit provided
            if (!($limit === strval(intval(strval($limit))))) {
                trigger_error('Invalid $limit `' . $limit . '` provided. Expecting an ' . 'integer', E_USER_WARNING);
                return $subject;
            }
            // Invalid $limit provided
            if ($limit < -1) {
                trigger_error('Invalid $limit `' . $limit . '` provided. Expecting -1 or ' . 'a positive integer', E_USER_WARNING);
                return $subject;
            }
            // No replacements necessary
            if ($limit === 0) {
                trigger_error('Invalid $limit `' . $limit . '` provided. Expecting -1 or ' . 'a positive integer', E_USER_NOTICE);
                return $subject;
            }
            // Use str_replace() when possible
            if ($limit === -1) {
                return str_replace($search, $replace, $subject, $count);
            }
            if (is_array($subject)) {
                // Loop through $subject values
                foreach ($subject as $key => $this_subject) {
                    // Skip values that are arrays
                    if (!is_array($this_subject)) {
                        // Call this function again
                        $this_function = __FUNCTION__;
                        $subject[$key] = $this_function($search, $replace, $this_subject, $this_count, $limit);
                        // Adjust $count
                        $count += $this_count;
                        // Adjust $limit
                        if ($limit != -1) {
                            $limit -= $this_count;
                        }
                        // Reached $limit
                        if ($limit === 0) {
                            return $subject;
                        }
                    }
                }
                return $subject;
            } elseif (is_array($search)) {
                // Clear keys of $search
                $search = array_values($search);
                // Clear keys of $replace
                if (is_array($replace)) {
                    $replace = array_values($replace);
                }
                // Loop through $search
                foreach ($search as $key => $this_search) {
                    // Don't support multi-dimensional arrays
                    $this_search = strval($this_search);
                    // If $replace is an array, use $replace[$key] if exists, else ''
                    if (is_array($replace)) {
                        if (array_key_exists($key, $replace)) {
                            $this_replace = strval($replace[$key]);
                        } else {
                            $this_replace = '';
                        }
                    } else {
                        $this_replace = strval($replace);
                    }
                    // Call this function again for
                    $this_function = __FUNCTION__;
                    $subject       = $this_function($this_search, $this_replace, $subject, $this_count, $limit);
                    // Adjust $count
                    $count += $this_count;
                    // Adjust $limit
                    if ($limit != -1) {
                        $limit -= $this_count;
                    }
                    // Reached $limit
                    if ($limit === 0) {
                        return $subject;
                    }
                }
                return $subject;
            } else {
                $search  = strval($search);
                $replace = strval($replace);
                // Get position of first $search
                $pos     = strpos($subject, $search);
                // Return $subject if $search cannot be found
                if ($pos === false) {
                    return $subject;
                }
                // Get length of $search
                $search_len = strlen($search);
                // Loop until $search cannot be found or $limit is reached
                for ($i = 0; (($i < $limit) || ($limit === -1)); $i++) {
                    $subject = substr_replace($subject, $replace, $pos, $search_len);
                    // Increase $count
                    $count++;
                    // Get location of next $search
                    $pos = strpos($subject, $search);
                    // Break out of loop
                    if ($pos === false) {
                        break;
                    }
                }
                return $subject;
            }
        }
    ?>
    

    【讨论】:

      【解决方案3】:

      只替换第一次出现的匹配字符串怎么样?

      <?php
      /**
       * replace only the first occurrence of str matched
       */
      function str_replace_first_only($from, $to, $content,$count)
      {
          $from = '/'.preg_quote($from, '/').'/';
          return preg_replace($from, $to, $content, $count); // remove only first occurrence
      }
      
      $patha = 'BIN/BIN/test.php';
      $count = 1;
      $pathb = str_replace_first_only('BIN', 'SYSTEM', $patha, $count);
      echo $pathb;
      ?>
      

      输出:

      SYSTEM/BIN/test.php
      

      工作演示: https://3v4l.org/OaVcP

      【讨论】:

        猜你喜欢
        • 2012-01-26
        • 2019-10-15
        • 2017-03-20
        • 1970-01-01
        • 2010-09-13
        • 1970-01-01
        • 2017-12-01
        • 2020-08-05
        • 1970-01-01
        相关资源
        最近更新 更多