tags:

views:

41

answers:

3

Same for example I have this:

Hello world!!
Hello all!

I want replace each "!" with a period for example. With PHP. How would I do that?

A: 
preg_replace('#\!+#s', 'what_ever_you_want', $subject)
WhoSayIn
Sorry about question but why you used this # and s symbols?
Centurion
The first character of a PCRE regexp is the delimiter, in this case the pound sign. After the ending delimiter may be placed a number of modifiers which change how the expression functions. In this case, the `s` modifier is being used.
erisco
# is delimiter, you can use what ever you want as a delimiter (except regex metacharacters i think, but im not sure) and "s" is a modifier which makes it multi-line compatible.
WhoSayIn
A: 

I figured out out. I cannot believe I didn't see this before. ! is a metacharacter so I need a '\' before it. That's why it wasn't working. Thanks.

Camoy
`!` is not a metacharacter. `preg_replace('/!/', '.', 'Hello world!!');` => `Hello world..`
Alan Moore
+5  A: 

Don't you think str_replace would suffice?

$str = str_replace('!','.',$str);
Robus
+1 No need for a regex here.
Daniel Vandersluis
No I need to do regex for other operations.
Camoy
I still don't see a reason to use regex, given your "With the same number of periods" comment. Note that str_replace can handle more than one character
Robus