473,383 Members | 1,864 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

preg_replace_callback() with create_function() and awkward strings

Hi all,

I'm trying to write a PHP colour parser and after various attempts,
something, somewhere trips it over. Some details:
String to parse:

$origString = '^1foo^5bar';
Required output:

<span style="color:#F00; background-color:transparent;">foo</span>
<span style="color:#F0F; background-color:transparent;">bar</span>
I have an array with all the HTML colour codes:

$cssColours = array(
'#000', '#F00', '#3F0', '#FF0',
'#00F', '#F0F', '#0FF', '#FFF', '#0E0'
);
One method I tried was:

$length = strlen($string);
for ($i = 0; $i < $length; $i++) {
if ($string[$i] == '^') {
if (is_numeric($string[$i + 1])) {
if (intval($string[$i + 1]) < 9) {
if (!$colour) {
$string = str_replace(
$string[$i] . $string[$i + 1],
'<span style="color:' . $cssColours[$string[$i + 1]] .
'; background-color:transparent;">',
$string
);
$colour = true;
} else {
$string = str_replace(
$string[$i] . $string[$i + 1],
'</span><span style="color:' . $cssColours[$string[$i + 1]] .
'; background-color:transparent;">',
$string
);
}
}
}
}
}
This "sort of" works although if the original string contains '^0' as a
colour code, no closing </span> tag is added (seems to work for all
other colours) but the other downside to this method is it's slow.

I then had a look at some regex that I thought might work. The code I
have for this is:
$string = stripslashes(substr(preg_replace_callback(
'`(?:\^([0-8]))`',
create_function(
'$matches',
'$cssColours = array("#000", "#F00", "#3F0", "#FF0", "#00F", "#F0F",
"#0FF", "#FFF", "#0E0"); return "</span><span style=\"color:" .
$cssColours[$matches[1]] . ";\">";'
),
quotemeta($string)
), 7)) . '</span>';
I know this is really tacky looking and it fails in some cases. When
feeding this:
echo $lfs->parseColourCodes('^0[^1TST^0]^1M^^0ike');
it produces (formatted for Usenet):
<span style="color:#000;">[</span>
<span style="color:#F00;">TST</span>
<span style="color:#000;">]</span>
<span style="color:#F00;">M^</span>
<span style="color:#000;">ike</span>
which is what I was expecting it to output. However, feeding it:
echo $lfs->parseColourCodes('^^^[^TST]M^^ike');
for example gives me:
^TST]M^^ike</span>
which is obviously not what I'm after =)

Someone did send me a solution they wrote but there's a whole class for
it alone (the code I'm writing is just a function within a class) and
was wondering if anyone had any ideas on this that might be solved with
a "simple" regex?

The legal colour codes that can be parsed are:
^0 - ^8
but ^ chars are perfectly ok just as carets(^boo^ etc).

The part I'm not understanding atm, is why the beginning of the string
is disappearing but it seems to be some kind of "pattern". For example,
feeding it this:
echo $lfs->parseColourCodes('^[^TST]M^^ike');
gives me:
T]M^^ike</span>
I've tried with and without the quotemeta() call (there can be pretty
much any symbolic char, so wasn't sure what might screw over the regex
pattern) but it's just not happening for me.

If anyone has any ideas / thoughts / suggestions, I'd be grateful in
hearing them as right now, I'm pretty stumped =)
TIA.

Regards,

Ian

--
Ian.H
digiServ Network
London, UK
http://digiserv.net/
Jul 17 '05 #1
3 2617
Ian.H wrote:
String to parse:

$origString = '^1foo^5bar';
Required output:

<span style="color:#F00; background-color:transparent;">foo</span>
<span style="color:#F0F; background-color:transparent;">bar</span>
[ ... ]

$string = preg_replace_callback(
'`\^([0-8])(.*?)(?=(?:\^[0-8])|\z)`',
create_function(
'$matches',
'$cssColours = array("#000", "#F00", "#3F0", "#FF0",
"#00F", "#F0F", "#0FF", "#FFF", "#0E0");
return "<span
style=\"color:{$cssColours[$matches[1]]};\"{$matches[2]}</span>";'),

$string);

See ciwas for arguments against inline styles.

HAGW!

--
Jock
Jul 17 '05 #2
On Fri, 15 Oct 2004 11:56:26 +0100, John Dunlop
<us*********@john.dunlop.name> wrote:
Ian.H wrote:
String to parse:

$origString = '^1foo^5bar';
Required output:

<span style="color:#F00; background-color:transparent;">foo</span>
<span style="color:#F0F; background-color:transparent;">bar</span>


[ ... ]

$string = preg_replace_callback(
'`\^([0-8])(.*?)(?=(?:\^[0-8])|\z)`',
create_function(
'$matches',
'$cssColours = array("#000", "#F00", "#3F0", "#FF0",
"#00F", "#F0F", "#0FF", "#FFF", "#0E0");
return "<span
style=\"color:{$cssColours[$matches[1]]};\"
>{$matches[2]}</span>";'),

$string);

See ciwas for arguments against inline styles.

HAGW!

Ahh John you're a diamond!

The only reason I opted for the create_function() call was because it
failed every time I tried to use either:
$this->someFunction()

or

FOO::someFunction()
I've never actually used this function before.. it came as a result of
using an array in preg_replace():
$string = preg_replace('/pattern/', "{$cssCodes[$1]}", $string);
and all other variations I could think of failing.

If there's a better way, I'm all for hearing! I didn't think this was
anywhere near a "perfect" solution.. just a possible solution =)

Thanks again for your answer.. I can now retain some hairs =D

Regards & good weekend to yourself...

Ian

--
Ian.H
digiServ Network
London, UK
http://digiserv.net/
Jul 17 '05 #3
On Fri, 15 Oct 2004 11:58:35 GMT, Ian.H <ia*@WINDOZEdigiserv.net> wrote:
[ snip ]
See ciwas for arguments against inline styles.

HAGW!


The only reason I opted for the create_function() call was because it
failed every time I tried to use either:


[ ... SNIP ... ]
Oops! I really misinterpreted this heh (it was late, very).

I don't use inline styles under normal circumstances, but this class is
being written for a "gaming community".. so I don't know what styles
they may / may not already have or want. This is also pretty much the
first release of this code and have thought about moving certain things
into a CSS file but don't know really how practical it'd be for a couple
of lines for this. When coding a site however, I never use inline
styles.. CSS all the way (along with XHTML) and validated naturally =)

Regards,

Ian

--
Ian.H
digiServ Network
London, UK
http://digiserv.net/
Jul 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: TheKeith | last post by:
Hi, I'm just learning php now for the first time and I'm having a little trouble understanding something. In the following example: ...
1
by: Colin McKinnon | last post by:
Hi all, The thing I'm doing just now uses create_function(). This works fine provided I don't do something silly in the code I am trying to incorporate. Is there any way I can check the syntax...
8
by: jody.florian | last post by:
Hi, I'm trying to use preg_replace_callback within a method. The preg_replace_callback() & mycallback() pair will only be used by this method, and this method will probably only be called once...
14
by: mens libertina | last post by:
Disclaimer: In addition to reading the skimpy entries at php.net, I've searched this group and alt.php to no avail. Basically, I'm trying to use a template to send email reminders, but I can't...
2
by: Kimmo Laine | last post by:
I tried to use a class member function as a callback in preg_replace_callback, but failed. It announces: " Warning: preg_replace_callback() : requires argument 2, 'myclass::myfunction', to be a...
0
by: Stephen Kay | last post by:
I'm having a problem where I changed hosts, went from php 4.1.2 to php 4.4.4, and now preg_replace_callback() is segfaulting when I pass it html that is longer than 2732 bytes. This code has worked...
8
by: lawrence k | last post by:
Just noticed this for the first time: http://us2.php.net/manual/en/function.create-function.php Anyone know if PHP supports enclosures, like Javascript or Ruby? I've always assumed PHP lacked...
2
by: Snaggy | last post by:
this is my problem: Class myClass { function process($matches) {return something($matches);} function myReplace($input) { return preg_replace_callback(/pattern/, '$this->process', $input)...
4
by: Jeff | last post by:
I've been struggling with this for a while. Here's what I'm trying to do: private function makeMiniTemplate($ARRAY){ /* $ARRAY looks like this: $ARRAY='Some Value';
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.