Page 1 of 1

Eregitation

Posted: Mon Jan 05, 2004 2:22 pm
by Gen-ik
Another eregi() question for those Gurus out there.

Is it possible to do some kind of if/else pattern search using eregi_replace() ?

What I am hoping to be able to do is change part of a link depending on where it's pointing. At the moment this is working fine for external links because I can match the http part, and with email addresses I can match the mailto: part.

The problems start with internal links (ie home.php) because I have nothing to search for (no http and no mailto)... so I guess the question is can I create a 'search pattern' that will only change links which don't contain http:// mailto: or javascript: ?

A simple example of what I'm doing at the moment is this...

Code: Select all

<?php

$f[] = "<a href="http:([^"]+)"";
$t[] = "<a href="http:\\1" onfocus="this.style.color='#ff0000'">";

$f[] = "<a href="mailto:([^"]+)"";
$t[] = "<a href="mailto:\\1" onfocus="this.style.color='#00ff00'">";

$f[] = "<a href="javascript:([^"]+)"";
$t[] = "<a href="javascript:\\1" onfocus="this.style.color='#0000ff'">";

foreach($f as $key => $value)
$buffer = eregi_replace($value, $t[$key], $buffer);

?>php
As a side note I need to include the "<a href=" bit otherwise it will also change <link> objects in the <head> of the page... which is not good.


As usual I would be very greatful for any help :)

Posted: Mon Jan 05, 2004 3:51 pm
by redmonkey
I don't know much about ereg, I tend to stick with preg. Using preg_replace() allows you to use an array for pattern and replacement. I've tacked one further $f[] and $t[] on the end which might work?

Code: Select all

<?php

$f[] = "/<a href="http:([^"]+)"/i";
$t[] = "<a href="http:$1" onfocus="this.style.color='#ff0000'">";

$f[] = "/<a href="mailto:([^"]+)"/i";
$t[] = "<a href="mailto:$1" onfocus="this.style.color='#00ff00'">";

$f[] = "/<a href="javascript:([^"]+)"/i";
$t[] = "<a href="javascript:$1" onfocus="this.style.color='#0000ff'">";

$f[] = "/<a href="([^:"]+)"/i";
$t[] = "<a href="$1" onfocus="this.style.color='#0000ff'">";

$buffer = preg_replace($f, $t, $buffer);

?>

Posted: Mon Jan 05, 2004 5:21 pm
by Gen-ik
Ahh, thanks redmonkey you've put me on the right track.
I've made it a bit simpler now by going for either internal or external links and the code now looks like this...

Code: Select all

<?php

// External Links
$f[] = "<a href="([^:]+): ([^"]+)""; // <<< There's a space in there otherwise an emoticon gets chucked in there by this forum!
$t[] = "<a href="\\1:\\2" onfocus="BlurLink(this,'ex')"";

// Internal Links
$f[] = "<a href="([^:"]+)"";
$t[] = "<a href="\\1" onfocus="BlurLink(this,'in')"";

foreach($f as $key => $value) 
$buffer = eregi_replace($value, $t[$key], $buffer); 

?>
PS. I stick with eregi because preg does my head in ;)

Thanks again.