1

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 "!".

3
  • 5
    Why not just use php.net/manual/en/function.str-replace.php? Commented Dec 8, 2016 at 13:54
  • 1
    Use an array with the str_replace then you can replace both characters. Commented Dec 8, 2016 at 13:56
  • I used that manual but it's works only with arrays Commented Dec 8, 2016 at 13:57

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It's works. thank you! but it's also replace "," to "!".
@MichaelShtefanitsa, just remove the comma between "o" and "l".
1

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/

Comments

1

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

Live Example

Comments

1

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

2 Comments

Why the comma in [l,o]?
It was a typo mistake, sorry.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.