Can I match and replace hash symbol with preg replace
andrewshim
3:02 pm on Feb 4, 2012 (gmt 0)
Can I match & replace a string that includes square brackets and hash? For example, I'd like to use preg_replace to replace all instances of "[F#]" with a number. So every time "[F#]" appears, it will be replaced with, say "3".
penders
4:08 pm on Feb 4, 2012 (gmt 0)
If you simply want to replace the literal string "[F#]" with "3" everywhere in your master string then you can just use str_replace() [uk3.php.net] - no need to use preg_replace() in this instance. Or is your pattern more complex than this?
rocknbil
4:11 pm on Feb 4, 2012 (gmt 0)
(or that . . . simul-post. :-) )
Try
$string = 'some verbiage and the following should be a 3: [F#]'; echo preg_replace('/\[\#F\]/','3',$string);
You may need to play with it but it's a start. The brackets need escaping because they normally represent a character class, the #, maybe not.
andrewshim
11:28 pm on Feb 4, 2012 (gmt 0)
I'm rushing to church...but I did a quick test, and the str_replace seems to work. I don't know why I kept using preg_replace. Aren't they the same?
thanks for the help too rocknbil.
I've just begun work on a small project for my Sunday School (kids' church) where I need to transpose chords (stored in a database) from one key to another.
penders
1:22 am on Feb 5, 2012 (gmt 0)
Aren't they the same?
They do a similar function, but they are very different. preg_replace() [uk3.php.net] is much more powerful and allows for complex regular expression patterns to be replaced, possibly using back references. str_replace() [uk3.php.net] simply replaces one string with another. preg_replace() can replace literal strings as well, but it is overkill and consequently slower. If you want to simply replace one static string with another then you should use str_replace() - it is quicker and easier.