Forum Moderators: coopster

Message Too Old, No Replies

preg_replace

         

mharzbone

4:54 am on Jan 30, 2006 (gmt 0)

10+ Year Member



Hi, i need help. Anybody can help me with this one?
$content = preg_replace('/(<a[^>]*href=[\'"])([^\'"?]+)([\'"].*>.*<\/a>)/iUs',"\\1\\2?ref=$ref\\3", $content);
I got that preg_replace change this sample: [domain.com...] to the right one which is [domain.com...] but what if i also have a link in my content which contains parameters like this one: [domain.com...] If i will use that preg_replace above it will change [domain.com...] to [domain.com...] which is already wrong. It should be [domain.com...] Please help me. I just studied preg_replace and I need it for refferal.

Salsa

6:58 am on Jan 30, 2006 (gmt 0)

10+ Year Member



Welcome to WebmasterWorld!

If I understand what you want, you might need to study preg_match, too.

With that, you might create an array of all the <a href ... > $matches in $content. You could then do a for loop to test which urls might already have a query string (?). If one does, you could explode on the? and then concatenate back together, like:

$replacements[$i]=$exploded_matches[0]."?ref=$ref&".$exploded_matchesl[1];

...else (if it doesn't have a?), assign a value to $replacements[$i] similar to your how you did your original preg_replace.

Then do your actual $content replacement for $matches[$i], like:

$content = preg_replace($matches[$i], $replacements[$i], $content);

...close the loop...some necessary punctuation may be missing here, but that's the kind of scheme I'd try.

I hope that helps,
Salsa

PS: On this forum, spaces are removed from before characters like "!" and "?" when you post, so watch for that when you're reading other's code.

mharzbone

8:42 am on Jan 30, 2006 (gmt 0)

10+ Year Member



I think i've tried that. On the first loop
[domain.com...] turns into
[domain.com...] and
[domain.com...] turns into
[domain.com...] but for
some reason it made a second loop and made my
[domain.com...] into
[domain.com...] Now, I've
made this one :

$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
$patterns = array('/(<a[^>]*href=[\'"])([^\'"?]+)([\'"].*>.*<\/a>)/iUs', '/(<a[^>]*href=[\'"])([^\'"]+)([\'"].*>.*<\/a>)/iUs');
$replacements = array("\\1\\2?ref=$ref\\3", "\\1\\2&ref=$ref\\3");
$content = preg_replace($patterns, $replacements, $content);
echo $content;
It still not works coz for some reason it made another loop. I got a question. How will I make a preg_replace that will find a link that contains "&"? I still got confuse with regex.

mharzbone

10:04 am on Jan 30, 2006 (gmt 0)

10+ Year Member



I got it dude! My idea works! hehe