I have a string "Hello World !" and I want to replace some letters in it and receive result like "He!!! W!r!d !" it's means that i changed all "l" and "o" to "!" I found function preg_replace();
function replace($s){
return preg_replace('/i/', '!', "$s");
}
and it works with exactly one letter or symbol, and I want to change 2 symbols to "!".
Change your function as such;
function replace($s) {
return preg_replace('/[ol]/', '!', $s);
}
Read more on regular expressions here to get further understanding on how to use regular expressions.
Since you are already using regular expressions, why not really use then to work with the pattern you are really looking for?
preg_replace('/l+/', '!', "Hello"); // "He!o" ,so rewrites multiple occurances
If you want exactly two occurances:
preg_replace('/l{2}/', '!', "Helllo"); // "He!lo" ,so rewrites exactly two occurances
Or what about that:
preg_replace('/[lo]/', '!', "Hello"); // "He!!!" ,so rewrites a set of characters
Play around a little using an online tool for such: https://regex101.com/
Using preg_replace
like you did:
$s = 'Hello World';
echo preg_replace('/[lo]/', '!', $s);
I think another way to do it would be to use an array
and str_replace
:
$s = 'Hello World';
$to_replace = array('o', 'l');
echo str_replace($to_replace, '!', $s);
This can be accomplished either using preg_replace()
like you're trying to do or with str_replace()
Using preg_replace()
, you need to make use of the |
(OR) meta-character
function replace($s){
return preg_replace('/l|o/', '!', "$s");
}
To do it with str_replace()
you pass all the letters that you want to replace in an array, and then the single replacing character as just a string (or, if you want to use multiple replacing characters, then also pass an array).
str_replace(array("l","o"), "!", $s);