As @bereal commented use the Regular Expression module re.sub.
Here's a simple example
Python:
>>> import re
>>> re.sub(r'([^A-Z])([A-Z])', r'\1_\2', 'camelCase').lower()
'camel_case'
And just for kicks here's it on PHP too:
<?php
echo strtolower(preg_replace('/([^A-Z])([A-Z])/', '$1_$2', 'camelCase'));
// prints camel_case
Answer from icc97 on Stack Overflowregex - python preg_replace translate message to gsm formatted message - Stack Overflow
Regex from Python in PHP - Stack Overflow
python .replace() regex - Stack Overflow
preg_replace - PHP Coding Help - PHP Freaks
No. Regular expressions in Python are handled by the re module.
article = re.sub(r'(?is)</html>.+', '</html>', article)
In general:
str_output = re.sub(regex_search_term, regex_replacement, str_input)
In order to replace text using regular expression use the re.sub function:
sub(pattern, repl, string[, count, flags])
It will replace non-everlaping instances of pattern by the text passed as string. If you need to analyze the match to extract information about specific group captures, for instance, you can pass a function to the string argument. more info here.
Examples
>>> import re
>>> re.sub(r'a', 'b', 'banana')
'bbnbnb'
>>> re.sub(r'/\d+', '/{id}', '/andre/23/abobora/43435')
'/andre/{id}/abobora/{id}'
I have working perl code that i need to implement in PHP. I'm looking for a PHP way to solve the problem instead of a translation.
I have a large array (array_push) of strings (some as json, some as html, some as forms), I have a set of strings to act as transform on each row. In Perl it's like,,,
<pre> foreach (@set){ foreach $k (keys %transform) { if (m/$k/) { $repl = $transform{$k}; s/$k/$repl/; } } } </pre>
for each element in a set execute a loop of looking for a pattern from an associative array/hash, if the key matches in the element, replace the matched key string with the string value from the hash.
so for each line in the set every pattern from the transform array is checked against the line; is there a better way to do this? i was thinking to use preg_replace_callback to match and replace with a lookup. Is there a way to cache the pattern match data. (otherwise every pattern in the transform (25?), is reprocessed for every line.