Reputation: 952
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?
Upvotes: 0
Views: 194
Reputation: 70480
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>
Upvotes: 2
Reputation: 93167
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 ?
Upvotes: 1
Reputation: 5340
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?
Upvotes: 1