2
$patha = 'BIN/BIN/test.php';
$count = 1;
$pathb = str_replace('BIN', 'SYSTEM', $patha, $count);
echo $pathb;

Result:

SYSTEM/SYSTEM/test.php

I want to replace only the first instance of BIN, so result should be:

SYSTEM/BIN/test.php

How to do this?

  • Possible duplicate of [PHP str\_replace() with a limit param?](https://stackoverflow.com/questions/8510223/php-str-replace-with-a-limit-param) – splash58 Dec 25 '18 at 11:10

3 Answers3

2

You should use preg_replace with $limit param

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

Because str_replace $count param is not limit as you waiting for

Nick
  • 138,499
  • 22
  • 57
  • 95
Maxim
  • 2,233
  • 6
  • 16
1

From the manual: PHP: str_replace - Manual, it clearly says the syntax here:

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

And then for the $count:

count
If passed, this will be set to the number of replacements performed.

It's not the number of replacements, the function is going to take. Your $count value gets updated telling that you have got 2 replacements made. To limit the number of replacements made, please use preg_replace. Or another function given in the manual:

<?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;
        }
    }
?>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

How about that with only replace first occurrence of matched string?

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

Output:

SYSTEM/BIN/test.php

Working DEMO: https://3v4l.org/OaVcP

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103