tags:

views:

42

answers:

3

I have a feeling that I might be missing something very basic. Anyways heres the scenario:

I'm using preg_replace to convert ===inputA===inputB=== to <a href="inputB">inputA</a>
This is what I'm using

$new = preg_replace('/===(.*?)===(.*?)===/', '<a href="$2">$1</a>', $old);

Its working fine alright, but I also need to further restrict inputB so its like this

preg_replace('/[^\w]/', '', every Link or inputB);

So basically, in the first code, where you see $2 over there I need to perform operations on that $2 so that it only contains \w as you can see in the second code. So the final result should be like this:
Convert ===The link===link's page=== to <a href="linkspage">The link</a>

I have no idea how to do this, what should I do?

+1  A: 

Try preg_match on the first one to get the 2 matches into variables, and then use preg_replace() on the one you want further checks on?

Fanis
+1  A: 

Why don't you do extract the matches from the first regex (preg_match) and treat thoses results and then put them back in a HTML form ?

Colin Hebert
I was thinking about this as well, however it would be a good idea to show some code on how to do this.
krike
Did a preg_match_all, then used str_replace in a loop and finally a preg_replace. But I posted the question because i was wondering if there was a way to perform operations directly on the "$2". Thanks anyway :)
gX
+1  A: 

Although there already is an accepted answer: this is what the /e modifier or preg_replace_callback() are for:

echo preg_replace(
    '/===(.*?)===(.*?)===/e',
    '"<a href=\"".preg_replace("/[^\w]/","","$2")."\">$1</a>"',
    '===inputA===in^^putB===');

//Output: <a href="inputB">inputA</a>

Or:

function _my_url_func($vars){
   return '<a href="'.strtoupper($vars[1]).'">'.$vars[2].'</a>';
}

echo preg_replace_callback(
    '/===(.*?)===(.*?)===/',
    '_my_url_func',
    '===inputA===inputB===');

//Output: <a href="INPUTA">inputB</a>
Wrikken
Wonderful, thats Exactly what I was looking for! Thanks!
gX