PHP » PYTHON |
login |
register |
about
|
PYTHON str_replace
is this article helpful?
|
Python replacement for PHP's str_replace
[
edit
| history
]
# replace all occurences: result = subject.replace(search, replace) Docs: http://docs.python.org/2/library/string.html#string.replace # to perform multiple replacements in one step: import re def multiple_replace(dic, text): pattern = "|".join(map(re.escape, dic.keys())) return re.sub(pattern, lambda m: dic[m.group()], text) # example: dic = { "Larry Wall" : "Guido van Rossum", "creator" : "Benevolent Dictator for Life", "Perl" : "Python", } print multiple_replace(dic, some_text) credits to: http://code.activestate.com/recipes/81330/ str_replace(PHP 4, PHP 5) str_replace — Replace all occurrences of the search string with the replacement string DescriptionThis function returns a string or an array with all occurrences of search in subject replaced with the given replace value. If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace(). ParametersIf search and replace are arrays, then str_replace() takes a value from each array and uses them to do search and replace on subject . If replace has fewer values than search , then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search . The converse would not make sense, though. If search or replace are arrays, their elements are processed first to last.
Return ValuesThis function returns a string or an array with the replaced values. Changelog
Examples
Example #1 str_replace() examples
<?php
Notes
See Also
|
more
Recently updated
more
Most requested
more
Last requests
|