Mcod Posted January 22, 2012 Share Posted January 22, 2012 Hi there, I am looking for some help to optimize some code. I am basically looking for a function which replaces the copyright sign followed by either a-z or 0-9 For example ©1 ©a ©abc ©2012 The thing is that I don't just want to replace the copyright sign - I want to replace it only if it is directly (without space) by either a number or a-z. Currently I am using $string = str_replace("©1","©1",$string); $string = str_replace("©2","©2",$string); $string = str_replace("©3","©3",$string); ... ... so it's using way too much space in my code. I am sure you know a better way to handle this don't you? Quote Link to comment Share on other sites More sharing options...
joe92 Posted January 23, 2012 Share Posted January 23, 2012 $string = preg_replace("/©([a-z0-9]+)/i","©\\1",$string); That should do it. That is looking for a copyright sign followed by a number or any letter between 1 and infinity times in lower or upper case and will replace it with ©\\1. The \\1 is the first capturing parenthesis (the round brackets) within the pattern so in your first example it will change too '©1'. If it detects a space the pattern will fail and so won't replace it. Hope that helps you, Joe Quote Link to comment Share on other sites More sharing options...
ragax Posted January 23, 2012 Share Posted January 23, 2012 Hi Mcod! The way your particular copyright symbols are encoded (not just ascii 169, but ascii 194 in front of it), I would go for something like this: Input: ©1 © leave it ©a ©abc ©2012 Code: <?php $regex=',[\xC2][\xA9]([[:alnum:]]),'; $string='©1 © leave it ©a ©abc ©2012 '; echo '<pre>'.htmlentities(preg_replace($regex, '©$1', $string)).'</pre>'; ?> Output: ©1 © leave it ©a ©abc ©2012 The weird  character seems to be part of how your © seems is encoded (ascii 194 / xC2 in front of the ascii 169 / xA9). But I'm an old Ascii man, so don't ask me about character encoding! I'm sure many people here can explain. (Maybe you can!) If you like, you can take out the  by replacing [\xC2][\xA9] with \xA9 Quote Link to comment Share on other sites More sharing options...
Mcod Posted January 25, 2012 Author Share Posted January 25, 2012 Thanks for your answers I used both solutions for two different parts of the script I am working on, as they fit both in very well. Thank you so much for all your help! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.