php str replace first
PHP str_replace() Function
Example
Replace the characters «world» in the string «Hello world!» with «Peter»:
Definition and Usage
The str_replace() function replaces some characters with some other characters in a string.
This function works by the following rules:
Note: This function is case-sensitive. Use the str_ireplace() function to perform a case-insensitive search.
Note: This function is binary-safe.
Syntax
Parameter Values
Parameter | Description |
---|---|
find | Required. Specifies the value to find |
replace | Required. Specifies the value to replace the value in find |
string | Required. Specifies the string to be searched |
count | Optional. A variable that counts the number of replacements |
Technical Details
Return Value: | Returns a string or an array with the replaced values |
---|---|
PHP Version: | 4+ |
Changelog: | The count parameter was added in PHP 5.0 |
Before PHP 4.3.3, this function experienced trouble when using arrays as both find and replace parameters, which caused empty find indexes to be skipped without advancing the internal pointer on the replace array. Newer versions will not have this problem.
As of PHP 4.0.5, most of the parameters can now be an array
More Examples
Example
Using str_replace() with an array and a count variable:
Example
Using str_replace() with fewer elements in replace than find:
PHP str_replace different for first instance
I’ve got the following str_replace code:
It basically replaces all instances of [++] with Name. However, i would like to only replace the first instance of the [++] with Name and all other instances should say He
Any idea how i can do this?
5 Answers 5
You can use preg_replace() instead of str_replace()
After this first replace, you can use str_replace() for all the other ++ to replace with «He».
If you just want to replace [++] for «Name» once, you should use preg_replace using the limit parameter, and then you can replace the rest of the string:
Just to toss in a one-row solution:
This will change all characters that start a sentence to uppercase, plus fix all your earlier issues.
Not the answer you’re looking for? Browse other questions tagged php str-replace or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
str_replace
(PHP 4, PHP 5, PHP 7, PHP 8)
str_replace — Replace all occurrences of the search string with the replacement string
Description
This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.
Parameters
If search or replace are arrays, their elements are processed first to last.
The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
The replacement value that replaces found search values. An array may be used to designate multiple replacements.
The string or array being searched and replaced on, otherwise known as the haystack.
If passed, this will be set to the number of replacements performed.
Return Values
This function returns a string or an array with the replaced values.
Examples
Example #1 Basic str_replace() examples
Example #2 Examples of potential str_replace() gotchas
Notes
Replacement order gotcha
Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.
This function is case-sensitive. Use str_ireplace() for case-insensitive replace.
See Also
User Contributed Notes 34 notes
A faster way to replace the strings in multidimensional array is to json_encode() it, do the str_replace() and then json_decode() it, like this:
>
?>
This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding.
Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row.
If you want to remove all dashes but one from the string ‘-aaa—-b-c——d—e—f’ resulting in ‘-aaa-b-c-d-e-f’, you cannot use str_replace. Instead, use preg_replace:
Be careful when replacing characters (or repeated patterns in the FROM and TO arrays):
To make this work, use «strtr» instead:
Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array.
$string = ‘I like to eat an apple with my dog in my chevy’ ;
// Echo: I like to eat an orange with my cat in my ford
?>
Here is the function:
Be aware that if you use this for filtering & sanitizing some form of user input, or remove ALL instances of a string, there’s another gotcha to watch out for:
// Remove all double characters
$string=»1001011010″;
$string=str_replace(array(«11″,»00″),»»,$string);
// Output: «110010»
$string=» ml> Malicious code html> etc»;
$string=str_replace(array(» «,» «),»»,$string);
// Output: » Malicious code etc»
This is what happens when the search and replace arrays are different sizes:
To more clearly illustrate this, consider the following example:
The following function utilizes array_combine and strtr to produce the expected output, and I believe it is the most efficient way to perform the desired string replacement without prior replacements affecting the final result.
This strips out horrible MS word characters.
Just keep fine tuning it until you get what you need, you’ll see ive commented some out which caused problems for me.
There could be some that need adding in, but its a start to anyone who wishes to make their own custom function.
There is an «invisible» character after the †for the right side double smart quote that doesn’t seem to display here. It is chr(157).
[] = ‘“’ ; // left side double smart quote
$find [] = ‘‒ ; // right side double smart quote
$find [] = ‘‘’ ; // left side single smart quote
$find [] = ‘’’ ; // right side single smart quote
$find [] = ‘…’ ; // elipsis
$find [] = ‘—’ ; // em dash
$find [] = ‘–’ ; // en dash
$replace [] = ‘»‘ ;
$replace [] = ‘»‘ ;
$replace [] = «‘» ;
$replace [] = «‘» ;
$replace [] = «. » ;
$replace [] = «-» ;
$replace [] = «-» ;
nikolaz dot tang at hotmail dot com’s solution of using json_encode/decode is interesting, but a couple of issues to be aware of with it.
json_decode will return objects, where arrays are probably expected. This is easily remedied by adding 2nd parameter ‘true’ to json_decode.
Might be worth mentioning that a SIMPLE way to accomplish Example 2 (potential gotchas) is to simply start your «replacements» in reverse.
So instead of starting from «A» and ending with «E»:
Using str_replace so that it only acts on the first match?
22 Answers 22
There’s no version of it, but the solution isn’t hacky at all.
Pretty easy, and saves the performance penalty of regular expressions.
The magic is in the optional fourth parameter [Limit]. From the documentation:
Though, see zombat’s answer for a more efficient method (roughly, 3-4x faster).
‘, which would help avoid the escaping problem to some degree. It depends what the data is, and where it came from.
Edit: both answers have been updated and are now correct. I’ll leave the answer since the function timings are still useful.
The answers by ‘zombat’ and ‘too much php’ are unfortunately not correct. This is a revision to the answer zombat posted (as I don’t have enough reputation to post a comment):
Note the strlen($needle), instead of strlen($replace). Zombat’s example will only work correctly if needle and replace are the same length.
Here’s the same functionality in a function with the same signature as PHP’s own str_replace:
This is the revised answer of ‘too much php’:
Note the 2 at the end instead of 1. Or in function format:
I timed the two functions and the first one is twice as fast when no match is found. They are the same speed when a match is found.
I wondered which one was the fastest, so I tested them all.
Below you will find:
All functions were tested with the same settings:
Functions that only replace the first occurrence of a string within a string:
Functions that only replace the last occurrence of a string within a string:
Unfortunately, I don’t know of any PHP function which can do this.
You can roll your own fairly easily like this:
I created this little function that replaces string on string (case-sensitive) with limit, without the need of Regexp. It works fine.
=> CODE WAS REVISED, so consider some comments too old
And thanks everyone on helping me to improve that
Any BUG, please communicate me; I’ll fix that up right after
Replacing the first ‘o’ to ‘ea’ for example:
The easiest way would be to use regular expression.
The other way is to find the position of the string with strpos() and then an substr_replace()
But i would really go for the RegExp.
Note: Whenever possible, str_replace_limit() will use str_replace() instead, so all calls to str_replace() can be replaced with str_replace_limit() without worrying about a hit to performance.
str_replace()
Синтаксис:
str_replace(search, replace, subject[, count])
Поддерживается следующими версиями PHP:
Описание функции:
Функции str_replace() производит замену одних символов в строке другими.
Обязательный аргумент. Строка или массив поиска
Использование функции str_replace() предпочтительнее использованию функции preg_replace(), так как работает быстрее.
Функция str_replace() отличается от функции str_ireplace() тем, что чувствительна к регистру.
Примеры:
Пример 1:
echo str_replace(«Вова»,»Дима»,»С добрым утром Вова!»);
?>
С добрым утром Дима!
Пример 2:
В этом примере показано использование массивов
$arr1 = array(«1″,»2″,»3»);
$arr2 = array(«a»,»b»,»c»);
echo str_replace($arr2,$arr1,»cabdfg»);
?>
Пример 3:
В этом примере показано использование массивов во всех аргументах
$arr1 = array(«1″,»2″,»3»);
$arr2 = array(«a»,»b»,»c»);
$arr3 = array(«t»,»c»,»a»);
print_r (str_replace($arr2,$arr1,$arr3));
?>