仅替换子字符串的第一个实例

时间:2018-12-25 09:41:04

标签: php

$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

该怎么做?

3 个答案:

答案 0 :(得分:2)

您应将preg_replace$limit参数一起使用

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

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

答案 1 :(得分:1)

在手册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;
        }
    }
?>

答案 2 :(得分:1)

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

<?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