Jump to content

Optimized Replacing


Mcod

Recommended Posts

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? :)

 

 

Link to comment
Share on other sites

$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

Link to comment
Share on other sites

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

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.